検索

このコンテンツは選択した言語では利用できません。

Chapter 54. Extending JAX-RS Endpoints with Swagger Support

download PDF

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.

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

Configuration examples

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

     …
}

54.2. JBoss Fuse CXF Implementations

Overview

This section describes how to use the SwaggerFeature in JBoss Fuse CXF implementations, in which REST services are defined inside JAR files and deployed to a JBoss Fuse container or a fabric8 container.

Your JBoss 7.1 installation contains a Quickstart (installDir/quickstarts/cxf/rest/) that demonstrates how to create a RESTful (JAX-RS) web service using CXF and how to enable Swagger and annotate the JAX-RS endpoints.

Enabling Swagger

Enabling Swagger involves:

  • Modifying the XML file that defines the CXF service by adding the CXF class (io.fabric8.cxf.endpoint.SwaggerFeature) to the <jaxrs:server> definition.

    For example:

    &lt;blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
    xmlns:cxf="http://cxf.apache.org/blueprint/core"
    xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0
    https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
    http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
    http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd"&gt;
    
       &lt;!-- The &lt;jaxrs:server/&gt; element sets up our JAX-RS services. It defines:
          - the server's address, '/crm', relative to the default CXF servlet URI with the
            default settings  the server will be running on 'http://localhost:8181/cxf/crm'
          - a list of service beans. in this example, we refer to another bean defined in this
    		Blueprint XML file with a &lt;ref/&gt; element    --&gt;
    
       &lt;jaxrs:server id="customerService" address="/crm"&gt;
           &lt;jaxrs:serviceBeans&gt;
               &lt;ref component-id="customerSvc"/&gt;
           &lt;/jaxrs:serviceBeans&gt;
           &lt;jaxrs:providers&gt;
               &lt;bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/&gt;
           &lt;/jaxrs:providers&gt;
           &lt;jaxrs:features&gt;
    	      *&lt;bean class=“io.fabric8.cxf.endpoint.SwaggerFeature” /&gt;*
    		   &lt;property name=“title” value=“Fabric8:CXF:Quickstarts - Customer Service” /&gt;
    	   	&lt;property name=“description” value=“Sample REST-based Customer Service” /&gt;
    		   &lt;property name=“version” value=“${project.version}” /&gt;
    	      &lt;/bean&gt;
           &lt;/jaxrs:features&gt;
        &lt;/jaxrs:server&gt;
    
    
        &lt;!-- We use the OSGi Blueprint XML syntax to define a bean referred to in the
        JAX-RS server setup. This bean carries a set of JAX-RS annotations that enable mapping
        its methods to incoming requests.  --&gt;
    
        &lt;bean id="customerSvc" class="io.fabric8.quickstarts.rest.CustomerService"/&gt;
    
    &lt;/blueprint&gt;
  • In the REST resource class:

Building and Deploying the Rest quickstart

See the README file in your JBoss Fuse 7.1 installDir/quickstarts/cxf/rest/ directory for instructions on how to build and deploy the rest quickstart.

Red Hat logoGithubRedditYoutubeTwitter

詳細情報

試用、購入および販売

コミュニティー

Red Hat ドキュメントについて

Red Hat をお使いのお客様が、信頼できるコンテンツが含まれている製品やサービスを活用することで、イノベーションを行い、目標を達成できるようにします。

多様性を受け入れるオープンソースの強化

Red Hat では、コード、ドキュメント、Web プロパティーにおける配慮に欠ける用語の置き換えに取り組んでいます。このような変更は、段階的に実施される予定です。詳細情報: Red Hat ブログ.

会社概要

Red Hat は、企業がコアとなるデータセンターからネットワークエッジに至るまで、各種プラットフォームや環境全体で作業を簡素化できるように、強化されたソリューションを提供しています。

© 2024 Red Hat, Inc.