4.5. Swagger Integration


Overview

You can use a Swagger service to create API documentation for any REST-defined routes and endpoints in a CamelContext file. To do this, use the Camel REST DSL with the camel-swagger-java module, which is purely Java-based. The camel-swagger-java module creates a servlet that is integrated with the CamelContext and that pulls the information from each REST endpoint to generate the API documentation in JSON or YAML format.
If you use Maven then edit your pom.xml file to add a dependency on the camel-swagger-java component:
<dependency>
   <groupId>org.apache.camel</groupId>
   <artifactId>camel-swagger-java</artifactId>
   <version>x.x.x</version>
   <!-- Specify the version of your camel-core module. --> 
</dependency>

Configuring a CamelContext to enable Swagger

To enable the use of the Swagger API in the Camel REST DSL, invoke apiContextPath() to set the context path for the Swagger-generated API documentation. For example:
public class UserRouteBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        // Configure the Camel REST DSL to use the netty4-http component:
        restConfiguration().component("netty4-http").bindingMode(RestBindingMode.json)
            // Generate pretty print output:
            .dataFormatProperty("prettyPrint", "true")
            // Set the context path and port number that netty will use:
            .contextPath("/").port(8080)
            // Add the context path for the Swagger-generated API documentation:
            .apiContextPath("/api-doc")
                .apiProperty("api.title", "User API").apiProperty("api.version", "1.2.3")
                // Enable CORS:
                .apiProperty("cors", "true");
 
        // This user REST service handles only JSON files:
        rest("/user").description("User rest service")
            .consumes("application/json").produces("application/json")
            .get("/{id}").description("Find user by id").outType(User.class)
                .param().name("id").type(path).description("The id of the user to get").dataType("int").endParam()
                .to("bean:userService?method=getUser(${header.id})")
            .put().description("Updates or create a user").type(User.class)
                .param().name("body").type(body).description("The user to update or create").endParam()
                .to("bean:userService?method=updateUser")
            .get("/findAll").description("Find all users").outTypeList(User.class)
                .to("bean:userService?method=listUsers");
    }
}

Swagger module configuration options

The options described in the table below let you configure the Swagger module. Set an option as follows:
  • If you are using the camel-swagger-java module as a servlet, set an option by updating the web.xml file and specifying an init-param element for each configuration option you want to set.
  • If you are using the camel-swagger-java module from Camel REST components, set an option by invoking the appropriate RestConfigurationDefinition method, such as enableCORS(), host(), or contextPath(). Set the api.xxx options with the RestConfigurationDefinition.apiProperty() method.
OptionTypeDescription
api.contact.emailStringEmail address to be used for API-related correspondence.
api.contact.nameStringName of person or organization to contact.
api.contact.urlStringURL to a website for more contact information.
apiContextIdListingBooleanIf your application uses more than one CamelContext object, the default behavior is to list the REST endpoints in only the current CamelContext. If you want a list of the REST endpoints in each CamelContext that is running in the JVM that is running the REST service then set this option to true. When apiContextIdListing is true then Swagger outputs the CamelContext IDs in the root path, for example, /api-docs, as a list of names in JSON format. To access the Swagger-generated documentation, append the REST context path to the CamelContext ID, for example, api-docs/myCamel. You can use the apiContextIdPattern option to filter the names in this output list.
apiContextIdPatternStringPattern that filters which CamelContext IDs appear in the context listing. You can specify regular expressions and use * as a wildcard. This is the same pattern matching facility as used by the Camel Intercept feature.
api.license.nameStringLicense name used for the API.
api.license.urlStringURL to the license used for the API.
api.pathStringSets the path where the REST API to generate documentation for is available, for example, /api-docs. Specify a relative path. Do not specify, for example, http or https. The camel-swagger-java module calculates the absolute path at runtime in this format: protocol://host:port/context-path/api-path.
api.termsOfServiceStringURL to the terms of service of the API.
api.titleStringTitle of the application.
api.versionStringVersion of the API. The default is 0.0.0.
base.pathStringRequired. Sets the path where the REST services are available. Specify a relative path. That is, do not specify, for example, http or https. The camel-swagger-java modul calculates the absolute path at runtime in this format: protocol://host:port/context-path/base.path.
corsBooleanWhether to enable HTTP Access Control (CORS). This enable CORS only for viewing the REST API documentation, and not for access to the REST service. The default is false. The recommendation is to use the CorsFilter option instead, as described after this table.
hostStringSet the name of the host that the Swagger service is running on. The default is to calculate the host name based on localhost.
schemesStringProtocol schemes to use. Separate multiple values with a comma, for example, "http,https". The default is http.
swagger.versionStringSwagger specification version. The default is 2.0.

Using the CORS filter to enable CORS support

If you use the Swagger user interface to view your REST API documentation then you probably need to enable support for HTTP Access Control (CORS). This support is required when the Swagger user interface is hosted and running on a hostname/port that is different from the hostname/port on which your REST APIs are running.
To enable support for CORS, add the RestSwaggerCorsFilter to your web.xml file. The CORS filter adds the HTTP headers that enable CORS. For example:
<!-- Enable CORS filter to allow use of Swagger UI for browsing and testing APIs. -->
<filter> 
     <filter-name>RestSwaggerCorsFilter</filter-name>
     <filter-class>org.apache.camel.swagger.rest.RestSwaggerCorsFilter</filter-class>
</filter>
<filter-mapping>
     <filter-name>RestSwaggerCorsFilter</filter-name>
     <url-pattern>/api-docs/*</url-pattern>
     <url-pattern>/rest/*</url-pattern>
</filter-mapping>
The RestSwaggerCorsFilter sets the following headers for all requests:
  • Access-Control-Allow-Origin= *
  • Access-Control-Allow-Methods = GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
  • Access-Control-Max-Age = 3600'
  • Access-Control-Allow-Headers = Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers
RestSwaggerCorsFilter is a simple filter. You might need a more sophisticated filter if you need to block certain clients or set the header values differently for a given client.

Obtaining JSON or YAML output

Starting with Camel 2.17, the camel-swagger-java module supports both JSON and YAML formatted output. To specify the output you want, add /swagger.json or /swagger.yaml to the request URL. If a request URL does not specify a format then the camel-swagger-java module inspects the HTTP Accept header to detect whether JSON or YAML can be accepted. If both are accepted or if none was set as accepted then JSON is the default return format.

Examples

In the Apache Camel distribution, camel-example-swagger-cdi and camel-example-swagger-java demonstrate the use of the camel-swagger-java module.

Enhancing documentation generated by Swagger

Starting with Camel 2.16, you can enhance the documentation generated by Swagger by defining parameter details such as name, description, data type, parameter type and so on. If you are using XML, specify the param element to add this information. The following example shows how to provide information about the ID path parameter:
<!-- This is a REST GET request to view information for the user with the given ID: -->
<get uri="/{id}" outType="org.apache.camel.example.rest.User">  
     <description>Find user by ID.</description>  
     <param name="id" type="path" description="The ID of the user to get information about." dataType="int"/>  
     <to uri="bean:userService?method=getUser(${header.id})"/>
</get>
Following is the same example in Java DSL:
.get("/{id}").description("Find user by ID.").outType(User.class) 
   .param().name("id").type(path).description("The ID of the user to get information about.").dataType("int").endParam() 
   .to("bean:userService?method=getUser(${header.id})")
If you define a parameter whose name is body then you must also specify body as the type of that parameter. For example:
<!-- This is a REST PUT request to create/update information about a user. -->
<put type="org.apache.camel.example.rest.User"> 
     <description>Updates or creates a user.</description> 
     <param name="body" type="body" description="The user to update or create."/>
     <to uri="bean:userService?method=updateUser"/>
</put>
Following is the same example in Java DSL:
.put().description("Updates or create a user").type(User.class)
     .param().name("body").type(body).description("The user to update or create.").endParam() 
     .to("bean:userService?method=updateUser")
See also: examples/camel-example-servlet-rest-tomcat in the Apache Camel distribution.
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.