RESTful API Documentation Using Swagger and Spring MVC

With the advancement of web technologies and different ways to implement them, there have been many different schools of thought about how to make it easy for end users and to address different challenges into the space of web. With this the inception of web-services proliferated majorily into two prime categories REST and SOAP.

Both of them are common way to expose web services, where SOAP has the significant contractual obligation between service consumer and service producer. It standardizes the request response structure through mutual understanding and adheres the contracts. But with RESTFul services the story is different. Describing to users how to use and interact with a REST API is a daunting task. There are no set standards to expose a REST contract other than HTTP method attributes governance. Many APIs resort to manually edited human-readable documentation, which is hard to maintain from a synchronization standpoint with the API. Hence, defining the standards for your REST services, and keeping the documentation updated in real time is a big challenge.

What is Swagger

Swagger is a specification for documenting REST API. It specifies the format (URL, method, and representation) to describe REST web services. Swagger is meant to enable the service producer to update the service documentation in real time so that client and documentation systems are moving at the same pace as the server. The methods, parameters, and models description are tightly integrated into the server code, thereby maintaining the synchronization in APIs and its documentation.

Swagger is the initiative of Wordnik, which defines the specification and framework for their internal development use for “develop.wordnik.com” and underlying system. They started developing the framework in early 2010—being released, is currently also used by Wordnik’s APIs, which powers both internal and external API clients.

Advantages

With the Swagger framework, the server, client and documentation team can be in synchronization simultaneously.

As Swagger is a language-agnostic specification, with its declarative resource specification, clients can easily understand and consume services without any prior knowledge of server implementation or access to the server code.

The Swagger UI framework allows both implementers and users to interact with the API. It gives clear insight into how the API responds to parameters and options.

Swagger responses are in JSON and XML, with additional formats in progress.

Swagger implementations are available for various technologies like Scala, Java, and HTML5.

Client generators are currently available for Scala, Java, JavaScript, Ruby, PHP, and Actionscript 3, with more client support underway.

With this, we attempt to expose the sample REST web-service with Spring MVC, and showcase the Swagger documentation.

Swagger Integration with Spring MVC.

In order to document the Spring MVC Rest API’s mention the following maven dependencies into the pom.xml.

<dependency>

            <groupId>com.mangofactory</groupId>

            <artifactId>swagger-springmvc</artifactId>

            <version>0.5.2</version>

</dependency>

This will cause the related Swagger artifacts, like swagger-core and swagger-annotations, to be included in your build path.

Mentioned are some of the following Annotations provided from wordnik Spring MVC for the Swagger project to document the Rest

  1. APIs.@Api
  2. @ApiClass
  3. @ApiError
  4. @ApiErrors
  5. @ApiOperation
  6. @ApiParam
  7. @ApiParamImplicit
  8. @ApiParamsImplicit
  9. @ApiProperty
  10. @ApiResponse
  11. @ApiResponses
  12. @ApiModel

In order to make use of the above-mentioned annotations in the controller, bind the swagger configuration bean into the mvc-context.xml.

<!-- Configuration Bean -->

<bean id="documentationConfig" class="com.mangofactory.swagger.configuration.DocumentationConfig"/>

Make sure to have these configurations enabled:

<context:annotation-config />

<mvc:default-servlet-handler/>

Create the swagger.properties with the following entries

documentation.services.version=1.0

documentation.services.basePath=http://<servername>:<port>/<context root>

and include the same in your application context the way any other property files are included.

Once these configurations are enabled, we can start using Swagger to document our controllers.

Mentioned below is the snippet of the controller to document the API and its methods.

@Controller     

@Api(value="onlinestore", description="Operations pertaining to Online Store")

@RequestMapping(value="/onlinestore")       

public class OnlineStoreController {

@Autowired

private IStoreFront storeFrontService;           

@ApiOperation(value = "View the Specific info of the product")

@RequestMapping(value="/authorize/viewProduct/{productid}", method=RequestMethod.GET)     

public ResponseEntity<Object> viewProduct(@ApiParam(name="productId", value="The Id of the product to be viewed", required=true) @PathVariable String productid, Model model){

The text mentioned in bold signifies the Swagger annotations for documenting the controller as required.

@Api-----> Narrates the description about what in general is the responsibility of the controller.

@ApiOperation----> Narrates the responsibility of the specific method.

@ApiParam--->Narrates the parameter the method is expecting and also tells whether it is mandatory or not.

(Note: These annotations support some more attributes which can be used as the necessity).

Similarly, you can document your model classes to provide the model schema, which helps in understanding/documenting the request response structure using the specific annotation using @ApiModel annotations.

Once done, the following can be deployed as a normal web app and the following URL can be hit in order to see the documentation.

http://<servername>:<port>/<context root>/api-docs, this will list all the controller related operations, as in our case:

<ApiDocumentation>

<apiVersion>1.0</apiVersion>

<apis>

<description>Operations pertaining to Online Store</description>

<path>/api-docs/onlinestore</path>

</apis>

<basePath>http://localhost:8080/onlineStore</basePath>

<swaggerVersion>1.0</swaggerVersion>

</ApiDocumentation>

The same can also be viewed using the SwaggerUI.

The Swagger UI comes with set CSS, JS and .JSP files which can be deployed and used to view the API documentations. (Swagger UI source)

This example shows how Swagger can be integrated with Spring MVC Rest APIs in order to document the same, and can have a seamless synchronization among implementation and documentations.

Wordnik provides many other out of the box Swagger frameworks that can be combined with other Java-related technologies like Servlet and CXF.