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.

Anubhav Gupta

Anubhav Gupta

Senior Technical Lead

Anubhav Gupta is a Senior Technical Lead at 3Pillar Global. He brings with him rich experience in designing/developing enterprise wide web applications and platforms. He has expertise on complete J2EE stack and technologies and has been majorily involved in designing/developing Products for Geospatial, Document Management and Banking domains. He likes to be driven by challenges and is passionate about learning new technologies/domains with prime area of interest being web platforms. Prior to joining 3Pillar Global, he has worked for various product and service based companies including Nucleus Export Ltd, Pitney Bowes Software, and RMSI.

24 Responses to “RESTful API Documentation Using Swagger and Spring MVC”
  1. PA on

    Hi Anubhav,

    Many thanks for providing such a nice article. I’m trying to make this example working, but not succeeded yet. May I request you to please provide your sample example? It will be great help for all who are following you. Looking for your soonest possible response.

    Thanks !

    Reply
  2. PA on

    Could you please share you code?

    Reply
  3. sandeep on

    Hi Abhinav,

    Thanks for this post. I am new to Web Services and Web APIs. But yes, have some basic understanding. From your post, Can I Infer, that documenting Rest API is probably the same thing as documenting the WSDL for SOAP based web services. Other than different names and annotations, it is almost the same thing? Now won’t it be a same challenge in future for APIs as happened for SOAP based services? I mean documenting the contracts, updating them and adhering to those? To me real question is Why it is needed? What problem arose for Dev/Test/ Ops which this documentation idea solved? Please advise.

    Thansk

    Reply
  4. Ketki on

    Hi,

    I am unable to view model using swagger . Could you please point me a link where I can find exact implementation of ApiModel

    Reply
  5. Ram on

    Any way to pull the documentation in the annotation from property files?

    Reply
  6. Diwakar on

    This does not work with @RestController in spring. Any help?
    When I add the swagger-springmvc dependency my spring application starts giving an error like
    @RestController can not be resolved.

    Reply
    • shubham on

      Hi Diwakar,

      Have u got any work around for @RestController
      if yes , then please share the solution

      Reply
      • Amar on

        have you have added dependency for spring mvc?

        Reply
      • Aneesha on

        To get the @RestController annotation working, just include the below dependency:

        org.springframework
        spring-context
        ${spring-framework.version}

        4.0.0.RELEASE

        Make sure that the spring version you have is 4.0. This annotation would not work with version 3.0

        Reply
  7. Irfan nasim on

    Hi Anubhav,

    my project have not spring mvc, but i have implemented it in my service class and api are annotated, how can i generate the docs?

    Reply
    • saad on

      Hi irfan,
      did you get to know how to use swagger without spring mvc? where do you put the swagger.properties file? Do reply.
      thanks

      Reply
  8. shubham on

    Hi,

    I followed all the steps given in this tut but wasn’t able to create api-doc on the specified URL.I guess problem might be with property file loading to application context.Can you share all the steps required for Property file, location to other configuration for property file . I am using Spring mvc in my project
    My controller also uses @RestController annotation

    Reply
  9. Savani on

    Hey, thank you. Could you please update your program for the latest Spring MVC Swagger dependencies too ?

    Reply
  10. Mithun Debnath on

    Hello,

    I have been able to implement it by following the steps.However my requirement is I want json response instead of XML. Can you please give me any advice in you have done something like this.

    Reply
  11. Ranjith on

    This seems like a major anti-pattern to me. Why pollute controller code with rather un-related documentation? Before you know this can get out of hand and one will have to go through 100s of annotations before they see actual code. It will be hard to see what the code is doing through the @forest.
    Rather, the reverse would work. Where we start with a YML file of API specification and forward engineer to create Spring MVC controllers.

    Reply
  12. Nisarg Raval on

    Hi I am using 0.5 greater version Question i am getting Model Schema in Swagger-UI
    please Help me out

    Reply
  13. Banamali MIshra on

    Hi Anubhav,

    Does Swagger is available for C++ language.

    Thank you.

    Reply
  14. kranthi on

    Hi

    @Api(value=”online store”, description=”Operations pertaining to Online Store”)
    In the above tag you are hard coding value and description ,is there an way to do in a standardized way.

    Reply
  15. Savani on

    Hi , Could you please share the source code ? It will help all your followers..

    Reply
  16. AJit on

    My Swagger UI is UP on local tomcat server but i am not able to fetch REST API through Swagger UI
    i am done with above steps but i am getting 404
    Plz tell me the solution

    Reply
  17. aru on

    hi,
    i tried out this code. I am able to see the api documentation. But the swagger tags i gave in controller is not getting displayed in the output xml.

    1.0
    http://localhost:8080/camp-redemption
    1.0

    This is what i get . Is there any configuration in web.xml to be made.

    Reply
  18. sreeram sathyam on

    I am not able to generate api-docs.json work spring 3.0.6 version can you please suggest.

    Reply
  19. Ace on

    Hi I have this error when running my Swaager rest with spring mvc.

    Caused by: java.lang.NoSuchMethodError: com/wordnik/swagger/annotations/Api.listingPath()Ljava/lang/String;
    at com.mangofactory.swagger.spring.ControllerAdapter.getListingPath(ControllerAdapter.java:51)
    at com.mangofactory.swagger.spring.ControllerAdapter.describeAsDocumentationEndpoint(ControllerAdapter.java:43)
    at com.mangofactory.swagger.spring.DocumentationReader.addEndpointDocumentationIfMissing(DocumentationReader.java:71)
    at com.mangofactory.swagger.spring.DocumentationReader.processMethod(DocumentationReader.java:92)
    at com.mangofactory.swagger.spring.DocumentationReader.buildMappingDocuments(DocumentationReader.java:53)
    at com.mangofactory.swagger.spring.DocumentationReader.(DocumentationReader.java:48)
    at com.mangofactory.swagger.spring.controller.DocumentationController.setServletContext(DocumentationController.java:58)
    at org.springframework.web.context.support.ServletContextAwareProcessor.postProcessBeforeInitialization(ServletContextAwareProcessor.java:103)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    … 71 more

    Reply
Leave a Reply