이 콘텐츠는 선택한 언어로 제공되지 않습니다.

Chapter 53. Extending JAX-RS Endpoints with Swagger Support


Abstract

CXF includes a SwaggerFeature (org.apache.cxf.jaxrs.swagger.SwaggerFeature), which extends published JAX-RS endpoints with support for Swagger. Swagger is fundamentally a JSON-based format used to describe RESTful services, like its predecessors WSDL and WADL, but much easier to use. For a detailed description, see Swagger.
The SwaggerFeature is supported in both standalone CXF and in JBoss Fuse implementations.

53.1. Standalone CXF Implementations

Overview

This section describes how to use the SwaggerFeature in a standalone CXF implementation, in which REST services are defined inside WAR files and deployed to a standalone web server, such as Tomcat.
Note
The project should be a Maven WAR project. After building and packaging it, you can deploy it to Tomcat by dropping the WAR file into the $TOMCAT_HOME/webapps directory.

Enabling Swagger

Enabling Swagger involves:
  • Modifying the XML file that defines the CXF service by adding the CXF class org.apache.cxf.jaxrs.swagger.SwaggerFeature to the <jaxrs:server> definition:
    <jaxrs:server id="xx" address="/address" />
        <jaxrs:features>
            <bean class="org.apache.cxf.jaxrs.swagger.SwaggerFeature"/>
        </jaxrs:features>
    </jaxrs:server>
    
    Copy to Clipboard Toggle word wrap
    See Example 53.1, “Example Swagger-enabled Spring configuration ” for an example of a Spring XML file for a Swagger-enabled CXF service.
  • In the REST resource class:
    • Importing the Swagger API annotations for each annotation required by the service:
      import com.wordnik.swgger.annotations.Api*
      where * = Api, ApiOperation, ApiParam, ApiResponse, ApiResponses, and so on.
    • Adding Swagger annotations to the JAX-RS annotated endpoints (@PATH, @PUT, @POST, @GET, @Produces, @Consumes, @DELETE, @PathParam, and so on).
      See Example 53.2, “Example REST resource with Swagger annotations” for an example of a Swagger-annotated REST resource class.

Configuration examples

Example 53.1. Example Swagger-enabled Spring configuration

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
	http://www.springframework.org/schema/beans  
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">

        <jaxrs:server id="customerService" address="/crm">
           <jaxrs:serviceBeans>
               <ref component-id="customerSvc"/>
           </jaxrs:serviceBeans>
           <jaxrs:providers>
               <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" />
           </jaxrs:providers>
           <jaxrs:features>
               <!-- include Swagger Feature -->
               <bean class=“org.apache.cxf.jaxrs.swagger.SwaggerFeature” />
           </jaxrs:features>
       </jaxrs:server>

	</beans>
Copy to Clipboard Toggle word wrap
This example shows only the relevant parts of a Swagger-annotated REST resource class.

Example 53.2. Example REST resource with Swagger annotations

...
                
import javax.annotation.Resource;
import javax.ws.rs.core.Context;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponses;
import com.wordnik.swagger.annotations.ApiResponse;

…

@Path("/customerservice/")
@Api(value = "/customerservice", description = "Operations about customerservice")
public class CustomerService {

    private static final Logger LOG = LoggerFactory.getLogger(CustomerService.class);

    long currentId = 123;
    Map<Long, Customer> = customers = new HashMap<Long, Customer>();
    Map<Long, Order> orders = new HashMap<Long, Order>();
    private MessageContext jaxrsContext;

    public CustomerService() {
        init();
    }

   @GET
    @Path("/customers/{id}/")
    @Produces("application/xml")
    @ApiOperation(value = "Find Customer by ID", notes = "More notes about this method", response = Customer.class)
    @ApiResponses(value = {
            @ApiResponse(code = 500, message = "Invalid ID supplied"),
            @ApiResponse(code = 204, message = "Customer not found")
            })
    public Customer getCustomer(@ApiParam(value = "ID of Customer to fetch", required = true) @PathParam("id") String id) {
        LOG.info("Invoking getCustomer, Customer id is: {}", id);
        long idNumber = Long.parseLong(id);
        Customer c = customers.get(idNumber);
        return c;
    }

    @PUT
    @Path("/customers/")
    @Consumes({ "application/xml", "application/json" })
    @ApiOperation(value = "Update an existing Customer")
    @ApiResponses(value = {
            @ApiResponse(code = 500, message = "Invalid ID supplied"),
            @ApiResponse(code = 204, message = "Customer not found")
            })
    public Response updateCustomer(@ApiParam(value = "Customer object that needs to be updated", required = true) Customer customer) {
        LOG.info("Invoking updateCustomer, Customer name is: {}", customer.getName());
        Customer c = customers.get(customer.getId());
        Response r;
        if (c != null) {
            customers.put(customer.getId(), customer);
            r = Response.ok().build();
        } else {
            r = Response.notModified().build();
        }

        return r;
    }

    @POST
    @Path("/customers/")
    @Consumes({ "application/xml", "application/json" })
    @ApiOperation(value = "Add a new Customer")
    @ApiResponses(value = { @ApiResponse(code = 500, message = "Invalid ID supplied"), })
    public Response addCustomer(@ApiParam(value = "Customer object that needs to be updated", required = true) Customer customer) {
        LOG.info("Invoking addCustomer, Customer name is: {}", customer.getName());
        customer.setId(++currentId);

        customers.put(customer.getId(), customer);
        if (jaxrsContext.getHttpHeaders().getMediaType().getSubtype().equals("json")) {
            return Response.ok().type("application/json").entity(customer).build();
        } else {
            return Response.ok().type("application/xml").entity(customer).build();
        }
    }
   
    @DELETE
    @Path("/customers/{id}/")
    @ApiOperation(value = "Delete Customer")
    @ApiResponses(value = {
            @ApiResponse(code = 500, message = "Invalid ID supplied"),
            @ApiResponse(code = 204, message = "Customer not found")
            })
    public Response deleteCustomer(@ApiParam(value = "ID of Customer to delete", required = true) @PathParam("id") String id) {
        LOG.info("Invoking deleteCustomer, Customer id is: {}", id);
        long idNumber = Long.parseLong(id);
        Customer c = customers.get(idNumber);

     …   
}
Copy to Clipboard Toggle word wrap
맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat