Swagger2Feature
The CXF Swagger2Feature allows you to generate Swagger 2.0 documents from JAX-RS service endpoints with a simple configuration.
For generating Swagger 1.2 documents, you can use SwaggerFeature instead of Swagger2Feature (for CXF versions <= 3.1.x).
These features can be configured programatically in Java or using Spring or Blueprint beans.
Setup
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-service-description-swagger</artifactId> <version>3.1.11</version> </dependency>
Note that a cxf-rt-rs-service-description needs to be used if older CXF 3.1.x versions are used.
Properties
The following optional parameters can be configured in Swagger2Feature
Note some properties listed below are not available or used differently in SwaggerFeature, as the corresponding properties are used differently in Swagger 2.0 and Swagger 1.2. Please refer to the corresponding Swagger documentation for more information.)
Name | Description | Default |
---|---|---|
basePath | the context root path+ | null |
contact | the contact information+ | null (in CXF 3.1.x "users@cxf.apache.org") |
description | the description+ | null (in CXF 3.1.x "The Application") |
filterClass | a security filter+ | null |
host | the host and port+ | null |
ignoreRoutes | excludes specific paths when scanning all resources (see scanAllResources)++ | null |
license | the license+ | "Apache 2.0 License" |
licenceUrl | the license URL+ | "http://www.apache.org/licenses/LICENSE-2.0.html" |
prettyPrint | when generating swagger.json, pretty-print the json document+ | false |
resourcePackage | a list of comma separated package names where resources must be scanned+ | a list of service classes configured at the endpoint |
runAsFilter | runs the feature as a filter | false |
scan | generates the swagger documentation+ | true |
scanAllResources | scans all resources including non-annotated JAX-RS resources++ | false |
schemes | the protocol schemes+ | null |
termsOfServiceUrl | the terms of service URL+ | null |
title | the title+ | null (in CXF 3.1.x "Sample REST Application") |
version | the version+ | null (in CXF 3.1.x "1.0.0") |
swaggerUiConfig | Swagger UI configuration | null |
Note: those descriptions marked with + correspond to the properties defined in Swagger's BeanConfig, and those marked with ++ correspond to the properties defined in Swagger's ReaderConfig.
Configuring from Code
import org.apache.cxf.frontend.ServerFactoryBean; import org.apache.cxf.jaxrs.swagger.Swagger2Feature; ... Swagger2Feature feature = new Swagger2Feature(); // customize some of the properties feature.setBasePath("/api"); // add this feature to the endpoint (e.g., to ServerFactoryBean's features) ServerFactoryBean sfb = new ServerFactoryBean(); sfb.getFeatures().add(feature);
Configuring in Spring
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation="http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> ... <!-- JAXRS providers --> <bean id="jsonProvider" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" /> <!-- Application resources --> <bean id="sampleResource" class="demo.jaxrs.swagger.server.Sample" /> <!-- CXF Swagger2Feature --> <bean id="swagger2Feature" class="org.apache.cxf.jaxrs.swagger.Swagger2Feature"> <!-- customize some of the properties --> <property name="basePath" value="/app/swaggerSample"/> </bean> ... <jaxrs:server id="sampleServer" address="/swaggerSample"> <jaxrs:serviceBeans> <ref bean="sampleResource" /> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="jsonProvider" /> </jaxrs:providers> <jaxrs:features> <ref bean="swagger2Feature" /> </jaxrs:features> </jaxrs:server> </beans>
Configuring in Blueprint
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/blueprint/core" xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs" xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd"> ... <!-- JAXRS providers --> <bean id="jsonProvider" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" /> <!-- Application resources --> <bean id="sampleResource" class="demo.jaxrs.swagger.server.Sample" /> <!-- CXF Swagger2Feature --> <bean id="swagger2Feature" class="org.apache.cxf.jaxrs.swagger.Swagger2Feature"> <!-- customize some of the properties --> <property name="basePath" value="/cxf/swaggerSample"/> </bean> ... <jaxrs:server id="sampleServer" address="/swaggerSample"> <jaxrs:serviceBeans> <ref component-id="sampleResource" /> </jaxrs:serviceBeans> <jaxrs:providers> <ref component-id="jsonProvider" /> </jaxrs:providers> <jaxrs:features> <ref component-id="swagger2Feature" /> </jaxrs:features> </jaxrs:server> </blueprint>
Configuring in CXFNonSpringJaxrsServlet
<web-app> <context-param> <param-name>contextParam</param-name> <param-value>contextParamValue</param-value> </context-param> <servlet> <servlet-name>CXFServlet</servlet-name> <display-name>CXF Servlet</display-name> <servlet-class> org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet </servlet-class> <init-param> <param-name>jaxrs.serviceClasses</param-name> <param-value> org.apache.cxf.systest.jaxrs.BookStore </param-value> </init-param> <init-param> <param-name>jaxrs.features</param-name> <param-value> org.apache.cxf.jaxrs.swagger.Swagger2Feature (basePath=/somepath) </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
New: Configuring from Properties file
Starting from CXF 3.1.13 and 3.2.0 it is possible to configure Swagger2Feature with a Properties file.
For example, while a samples/jax_rs/spring_boot demo configures the feature from the code, a samples/jax_rs/spring_boot_scan demo has it configured from the properties file.
Default location for a properties file is "/swagger.properties". Swagger2Feature will pick it up if it is available, and the location can be overridden with a new Swagger2Feature 'swaggerPropertiesLocation' property.
Note that the properties, if available, do not override the properties which may have been set as suggested above from the code or Spring/Blueprint contexts or web.xml. Instead they complement and serve as the default configuration properties: for example, if some properties have been set from the code then the values for the same properties found in the properties file will not be used.
Enabling in Spring Boot
See samples/jax_rs/spring_boot and on how to create Swagger2Feature in a @Bean method or/and samples/jax_rs/spring_boot_scan on how to auto-enable it.
Accessing Swagger Documents
When Swagger is enabled by Swagger feature, the Swagger documents will be available at the location URL constructed of the service endpoint location followed by /swagger.json or /swagger.yaml.
For example, lets assume a JAX-RS endpoint is published at 'http://host:port/context/services/' where 'context' is a web application context, "/services" is a servlet URL. In this case its Swagger documents are available at 'http://host:port/context/services/swagger.json' and 'http://host:port/context/services/swagger.yaml'.
Starting from CXF 3.1.7 the CXF Services page will link to Swagger documents if Swagger2Feature is active.
In the above example, go to 'http://host:port/context/services/services' and follow a Swagger link which will return a Swagger JSON document.
If CORS support is needed to access the definition from a Swagger UI on another host, the CrossOriginResourceSharingFilter from cxf-rt-rs-security-cors can be added.
Enabling Swagger UI
First one needs to add the following
<dependency> <groupId>org.webjars</groupId> <artifactId>swagger-ui</artifactId> <version>2.2.10-1</version> </dependency>
The newest version 3.x of swagger-ui can also be used.
Enabling Swagger UI in OSGi container (Karaf)
Since org.webjars/swagger-ui is just a package with resources, it won't be referenced in OSGi manifest as the required imports. Therefore, to make use of Swagger UI in the OSGi deployments, the org.webjars/swagger-ui should be installed manually, for example:
karaf@root()> install mvn:org.webjars/swagger-ui/3.23.8
The dedicated Activator will take care of discovering the presence of the org.webjars/swagger-ui bundle and configuring Swagger2Feature.
Automatic UI Activation
This feature is available starting from CXF 3.1.7: Adding a Swagger UI Maven dependency is all what is needed to start accessing Swagger documents with the help of Swagger UI.
For example, lets assume a JAX-RS endpoint is published at 'http://host:port/context/services/'.
Open the browser and go to 'http://host:port/context/services/api-docs/?url=/swagger.json' which will return a Swagger UI page.
CXF Services page will also link to Swagger UI. Go to 'http://host:port/context/services/services' and follow a Swagger link which will return a Swagger UI page.
See samples/jax_rs/description_swagger2, samples/jax_rs/description_swagger2_web, samples/jax_rs/spring_boot and samples/jax_rs/spring_boot_scan
Note that CXF OSGI endpoints can only depend on this feature starting from CXF 3.1.8.
Unpacking Swagger UI resources
Up until CXF 3.1.7 unpacking Swagger UI resources into the local folder was the only option. It is demoed in samples/jax_rs/description_swagger2_spring and samples/jax_rs/description_swagger2_osgi.
In CXF 3.1.8: set Swagger2Feature 'supportSwaggerUi' property to 'false' to disable the automatic UI activation described in the previous section
Configuring Swagger UI (3.2.7+)
The Swagger2Feature has a way to pre-configure certain Swagger UI parameters (https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md) through SwaggerUiConfig. The way it is implemented is by passing those parameters as a query string so the Swagger UI could adjust itself.
Apache CXF prior to 3.4.6 / 3.5.1 passed Swagger UI configuration (url, ...) as query parameters. Starting from Swagger UI 4.1.3, most of query parameters are not accepted anymore (due to security concerns), and Apache CXF employes different strategy and tries to replace the URL dynamically (inside HTML) when serving Swagger UI's front web page. This behaviour could be turned off by setting queryConfigEnabled
property of the SwaggerUiConfig to true
(the default value is false
and URLs are replaced dynamically). Please notice that in this case the customized Swagger UI bundle is required since queryConfigEnabled
property could only be set by altering the distribution (https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md).
The typical initialization for server-side dynamical URL replacement looks like this:
new SwaggerUiConfig() .url("/swagger.json") ... .queryConfigEnabled(false)
In other words:
- when
queryConfigEnabled
is set to false, Apache CXF will dynamically replace the URL in SwaggerUI, in this respect the value won't be taken from the query string but fromurl
property of the SwaggerUI configuration, this is a default behavior - when
queryConfigEnabled
is set to true, Apache CXF will do nothing and just forward query parameters to SwaggerUI (hoping it will somehow take care of it), in general that implies custom SwaggerUI distribution has to be used
Reverse Proxy
Set a CXFServlet init parameter 'use-x-forwarded-headers' to 'true' if you access Swagger JSON and/or UI via the reverse proxy. If you use CXF SpringBoot starters then this property is prefixed with a "cxf.servlet.init.", "cxf.servlet.init.use-x-forwarded-headers".
You may also need to set Swagger2Feature 'usePathBasedConfig' property to 'true' to prevent Swagger from caching the 'basePath' value.
Converting to OpenAPI JSON
OpenAPI specification has been released and the CXF team has started working on the new feature which will produce OpenAPI JSON with the help of the new core and jaxrs libraries being currently developed by the Swagger community.
In meantime, while the new feature development is taking place, one can experiment with converting the Swagger JSON produced by CXF Swagger2Feature into Open API JSON.
All what is needed is registering SwaggerToOpenApiConversionFilter with the JAX-RS endpoint and requesting an "openapi.json" as opposed to "swagger.json". The filter will let Swagger2Feature generate JSON as usual and then convert the response to OpenAPI JSON if requested by the user or leave it intact otherwise. By issuing either "swagger.json" or "openapi.json" queries one can easily see the difference between the two formats.
The cxf-rt-rs-json-basic dependency must be on the classpath as well.
Note, OpenAPI JSON (see also OpenApiFeature) allows referring to its new "components/requestBodies" section from the multiple "requestBody" elements (which can be found under the specific path/http verb sub-sections). By default the filter will instead inline the the "requestBody" definitions inside of "requestBody" elements, but one can experiment with referring to the "components/requestBodies" by configuring the filter to create the request bodies.
The conversion filter is available starting from CXF 3.1.15 and 3.2.2
Samples
CXF's distribution contains the following samples.
- samples/jax_rs/description_swagger: Swagger 1.2 sample using SwaggerFeature programatically
- samples/jax_rs/description_swagger2: Swagger 2.0 standalone sample using Swagger2Feature programatically
- samples/jax_rs/description_swagger2_spring: Swagger 2.0 standalone sample using Swagger2Feature using Spring
- samples/jax_rs/description_swagger2_web: Swagger 2.0 web application sample using Swagger2Feature using Spring
- samples/jax_rs/description_swagger2_osgi: Swagger 2.0 OSGi application sample using Swagger2Feature using Blueprint
9 Comments
Justin Holmes
I'd like to submit some fixes to this documentation e.g. paths being incorrect and also info about the new OpenAPIFeature. How do I submit a PR or something like that?
Andriy Redko
Thanks Justin. Are you able to add inline comments (right where the issues are)? The OpenApiFeature has been added (OpenApiFeature).
Justin Holmes
Appears so. I'll provide input that way.
Sanath Kumar
Team, I am using "CXFNonSpringJaxrsServlet" in my project. But i am not able to access any urls provided. No json or yaml files created. Please guide me.
Sanath Kumar
Also which examples I need to refer from the list.
Andriy Redko
Hey Sanath Kumar, The samples/jax_rs/description_swagger2 is a complete example which uses "CXFNonSpringJaxrsServlet".
Sanath Kumar
Thank you. It worked.
Rajeswara Reddy Valishekkagari
@annotations Api and annotation Path are not working together getting the following exception
used combination
dependency projects use codehaus(jackson1, so there are two jackson1 and jackson2 combination) and can't exclude the dependency as the objectMappers fail to convert to jackson2 from jackson1
14:33:46.089 [localhost-startStop-1] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restContainer': Invocation of init method failed; nested exception is org.apache.cxf.service.factory.ServiceConstructionException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
Caused by: java.lang.IllegalArgumentException: Unrecognized Type: [null]
at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1237) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeFactory.java:631) ~[jackson-databind-2.9.9.jar:2.9.9]
If I remove one of API/path it works but does not show any APIS in swagger UI, they show as "No Specifications Found"
ANY HELP WOULD BE HIGHLY APPRECIATED
Andriy Redko
Hi Rajeswara Reddy Valishekkagari ,
Please post the issue on users / dev mailing lists [0], Confluence is not a good place for that. Meantime, it would be good to have a sample project attached since it is unclear how things are wired together. Thank you.
[0] http://cxf.apache.org/mailing-lists.html
Best Regards,
Andriy Redko