Since we're on a major migration process of this website, some component documents here are out of sync right now. In the meantime you may want to look at the early version of the new website
https://camel.apache.org/staging/
We would very much like to receive any feedback on the new site, please join the discussion on the Camel user mailing list.

Swagger Java Component

Available as of Camel 2.16

The  Rest DSL can be integrated with the camel-swagger-java module which is used for exposing the REST services and their APIs using Swagger.

Maven users will need to add the following dependency to their pom.xml for this component:

From Camel 2.16 onwards the swagger component is purely Java based, and its 

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-swagger-java</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

 

The camel-swagger-java module can be used as a Servlet or directly from the REST components (without the need for servlet)

 For an example see the camel-example-swagger-cdi in the examples directory of the Apache Camel distribution.

 

Using Swagger as a Servlet

You configure the swagger in the web.xml as shown below:

  <servlet>
 
    <servlet-name>SwaggerServlet</servlet-name>
    <servlet-class>org.apache.camel.swagger.servlet.RestSwaggerServlet</servlet-class>

    <init-param>
      <!-- we specify the base.path using relative notation, that means the actual path will be calculated at runtime as
           http://server:port/contextpath/rest -->
      <param-name>base.path</param-name>
      <param-value>rest</param-value>
    </init-param>
    <init-param>
      <!-- we specify the api.path using relative notation, that means the actual path will be calculated at runtime as
           http://server:port/contextpath/api-docs -->
      <param-name>api.path</param-name>
      <param-value>api-docs</param-value>
    </init-param>

    <init-param>
      <param-name>api.version</param-name>
      <param-value>1.2.3</param-value>
    </init-param>
    <init-param>
      <param-name>api.title</param-name>
      <param-value>User Services</param-value>
    </init-param>
    <init-param>
      <param-name>api.description</param-name>
      <param-value>Camel Rest Example with Swagger that provides an User REST service</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- swagger api -->
  <servlet-mapping>
    <servlet-name>SwaggerServlet</servlet-name>
    <url-pattern>/api-docs/*</url-pattern>
  </servlet-mapping>

Using Swagger in rest-dsl

You can enable the swagger api from the rest-dsl by configuring the apiContextPath dsl as shown below:

public class UserRouteBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        // configure we want to use servlet as the component for the rest DSL
        // and we enable json binding mode
        restConfiguration().component("netty4-http").bindingMode(RestBindingMode.json)
            // and output using pretty print
            .dataFormatProperty("prettyPrint", "true")
            // setup context path and port number that netty will use
            .contextPath("/").port(8080)
            // add swagger api-doc out of the box
            .apiContextPath("/api-doc")
                .apiProperty("api.title", "User API").apiProperty("api.version", "1.2.3")
                // and enable CORS
                .apiProperty("cors", "true");

        // this user REST service is json only
        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");
    }
}

 

Options

The swagger module can be configured using the following options. To configure using a servlet you use the init-param as shown above. When configuring directly in the rest-dsl, you use the appropriate method, such as enableCORShost,contextPath, dsl. The options with api.xxx is configured using apiProperty dsl.

Option

Type

Description

corsBooleanWhether to enable CORS. Notice this only enables CORS for the api browser, and not the actual access to the REST services. Is default false.
Instead of using this option is recommended to use the CorsFilte, see further below.
swagger.versionStringSwagger spec version. Is default 2.0.
hostStringTo setup the hostname. If not configured camel-swagger-java will calculate the name as localhost based.
schemasStringThe protocol schemes to use. Multiple values can be separated by comma such as "http,https". The default value is "http". This option is deprecated from Camel 2.17 onwards due it should have been named schemes.
schemesStringCamel 2.17: The protocol schemes to use. Multiple values can be separated by comma such as "http,https". The default value is "http".
base.path

 

String

Required: To setup the base path where the REST services is available. The path is relative (eg do not start with http/https) and camel-swagger-java will calculate the absolute base path at runtime, which will be

protocol://host:port/context-path/base.path
api.pathString

To setup the path where the API is available (eg /api-docs). The path is relative (eg do not start with http/https) and camel-swagger-java will calculate the absolute base path at runtime, which will be

protocol://host:port/context-path/api.path

So using relative paths is much easier. See above for an example.

api.versionStringThe version of the api. Is default 0.0.0.
api.titleStringThe title of the application.
api.descriptionStringA short description of the application.
api.termsOfServiceStringA URL to the Terms of Service of the API.
api.contact.nameStringName of person or organization to contact
api.contact.emailStringAn email to be used for API-related correspondence.
api.contact.urlStringA URL to a website for more contact information.
api.license.nameStringThe license name used for the API.
api.license.urlStringA URL to the license used for the API.
apiContextIdListingbooleanWhether to allow listing all the CamelContext names in the JVM that has REST services. When enabled then the root path of the api-doc will list all the contexts. When disabled then no context ids is listed and the root path of the api-doc lists the current CamelContext. Is default false.
apiContextIdPatternStringA pattern that allows to filter which CamelContext names is shown in the context listing. The pattern is using regular expression and * as wildcard. Its the same pattern matching as used by Intercept

CorsFilter

If you use the swagger ui to view the REST api then you likely need to enable support for CORS. This is needed if the swagger ui is hosted and running on another hostname/port than the actual REST apis. When doing this the swagger ui needs to be allowed to access the REST resources across the origin (CORS). The CorsFilter adds the necessary HTTP headers to enable CORS.

To use CORS adds the following filter org.apache.camel.swagger.servlet.RestSwaggerCorsFilter to your web.xml.

  <!-- enable CORS filter so people can use swagger ui to browse and test the apis -->
  <filter>
    <filter-name>RestSwaggerCorsFilter</filter-name>
    <filter-class>org.apache.camel.swagger.servlet.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 CorsFilter 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

Notice this is a very simple CORS filter. You may need to use a more sophisticated filter to set the header values differently for a given client. Or block certain clients etc.

ContextIdListing enabled

When contextIdListing is enabled then its detecting all the running CamelContexts in the same JVM. These contexts are listed in the root path, eg `/api-docs` as a simple list of names in json format. To access the swagger documentation then the context-path must be appended with the Camel context id, such as `api-docs/myCamel`. The option apiContextIdPattern can be used to filter the names in this list.

JSon or Yaml

Available as of Camel 2.17

The camel-swagger-java module supports both JSon and Yaml out of the box. You can specify in the request url what you want returned by using /swagger.json or /swagger.yaml for either one. If none is specified then the HTTP Accept header is used to detect if json or yaml can be accepted. If either both is accepted or none was set as accepted then json is returned as the default format.

Examples

In the Apache Camel distribution we ship a number of Swagger examples which demonstrates using this Swagger component.


© 2004-2015 The Apache Software Foundation.
Apache Camel, Camel, Apache, the Apache feather logo, and the Apache Camel project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners.
Graphic Design By Hiram