REST API documentation via Swagger

Why Swagger?

Swagger is an open source framework for designing and describing APIs. Swagger has become the de-facto standard for designing and describing RESTful APIs used by millions of developers and organisations for developing their APIs, be it internal or client facing. The current version of Swagger is 2.0. Swagger can be written in JSON or YAML which makes it easier to read and understand.

Enable Swagger for CXF Spring based REST APIs

Integrationing swagger with well-known frameworks such as Jersey (1.x, 2.x), RESTEasy, Mule are well documented in Swagger Site. In this post, we will know about one of the way to enable Swagger for RESTful APIs developed using JAXRS support of Apache CXF library.

Enable in Maven Project for CXF version (> 3.1.x)


Enable Swagger2Feature in your spring configuration

<bean id="swagger2Feature" class="org.apache.cxf.jaxrs.swagger.Swagger2Feature">
 <property name="basePath" value="/demo-app/services" /> 
 <property name="resourcePackage" value="" />


Add Swagger2Feature to JaxRs Component of CXF Configuration

<jaxrs:server id="rs" address="/services">
      <ref bean="swagger2Feature" /> 

Enable Swagger-UI

Copy Swagger-UI contents inside your java app/microservice’s webapp folder as shown below. You can download swagger-ui zip from here, swagger-ui

Screen Shot 2017-11-22 at 7.56.53 PM

swagger-ui contents with index.html


Change url content inside index.html to point to generated swagger json of your app

Screen Shot 2017-11-22 at 8.16.46 PM


Enabling Swagger on sample demo endpoint

The swagger annotations such as @ApiOperation, @ApiResponse on your resource classes are identified by swagger annotations processor at runtime to generate swagger.json|yaml.

@ApiOperation(value = "demo api")
@ApiResponses(value = {
 @ApiResponse(code = 201, message = "demo item got created successfully"),
 @ApiResponse(code = 400, message = "demo item request object in invalid"),
 @ApiResponse(code = 500, message = "error while creating demo item")
public Response createDemoItem(@ApiParam(value = "demo item request", required = true) DemoItemRequest demoItemRequest) throws DemoAppException;

You can read more about Swagger annotations here, Swagger annotations

Finally, we should be able to view your documented REST APIs at one place as shown below.

The typical url in an app/micro service/web application would take this pattern

Sample Image taken from Google search. Sample Swagger-UI rendering all identified APIs.


Further reading…

Why Swagger

CXF Swagger Integration

Swagger UI