此内容没有您所选择的语言版本。

Chapter 51. 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.

51.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>
    
    See Example 51.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 51.2, “Example REST resource with Swagger annotations” for an example of a Swagger-annotated REST resource class.

Configuration examples

Example 51.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>
This example shows only the relevant parts of a Swagger-annotated REST resource class.

Example 51.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);

     …   
}
Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.