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) <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-service-description-swagger</artifactId> <version>3.1.11</version> </dependency> 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="com.demo.app.resources" /> </bean>

 

Add Swagger2Feature to JaxRs Component of CXF Configuration <jaxrs:server id="rs" address="/services"> ... <jaxrs:features> <ref bean="swagger2Feature" /> </jaxrs:features> ... </jaxrs:server> 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

swagger-ui contents with index.html

 

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

 

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.

@POST @Path("demo") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @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

http://demo.server.com/api/swagger-ui/index.html

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

 

Further reading…

Why Swagger

CXF Swagger Integration

Swagger UI

Advertisements Share this:
Like this:Like Loading...