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 theweb.xml
file and specifying aninit-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 appropriateRestConfigurationDefinition
method, such asenableCORS()
,host()
, orcontextPath()
. Set theapi.
options with thexxx
RestConfigurationDefinition.apiProperty()
method.
Option | Type | Description |
---|---|---|
api.contact.email | String | Email address to be used for API-related correspondence. |
api.contact.name | String | Name of person or organization to contact. |
api.contact.url | String | URL to a website for more contact information. |
apiContextIdListing | Boolean | If 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. |
apiContextIdPattern | String | Pattern 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.name | String | License name used for the API. |
api.license.url | String | URL to the license used for the API. |
api.path | String | Sets 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: . |
api.termsOfService | String | URL to the terms of service of the API. |
api.title | String | Title of the application. |
api.version | String | Version of the API. The default is 0.0.0. |
base.path | String | Required. 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: . |
cors | Boolean | Whether 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. |
host | String | Set the name of the host that the Swagger service is running on. The default is to calculate the host name based on localhost . |
schemes | String | Protocol schemes to use. Separate multiple values with a comma, for example, "http,https". The default is http . |
swagger.version | String | Swagger 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.