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 “” 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.


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.






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 />


Create the with the following entries<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.


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


public class OnlineStoreController {


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:




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






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.

26 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 !

  2. PA on

    Could you please share you code?

  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.


  4. Ketki on


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

  5. Ram on

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

  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.

    • shubham on

      Hi Diwakar,

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

      • Amar on

        have you have added dependency for spring mvc?

      • Aneesha on

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



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

  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?

    • saad on

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

  8. shubham on


    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

  9. Savani on

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

  10. Mithun Debnath on


    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.

  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.

  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

  13. Banamali MIshra on

    Hi Anubhav,

    Does Swagger is available for C++ language.

    Thank you.

  14. kranthi on


    @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.

  15. Savani on

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

  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

  17. chiranj on


    I am getting an error on server startup.
    java.lang.IllegalArgumentException: Could not resolve placeholder ‘’ in string value “${}”
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(

  18. Aishwarya Gupta on

    I want to have the values of my variable at only one place (something like property file) rather than using @ApiModelProperty() annotation in class.

    public class RequestBean {
    @ApiModelProperty(example = “agupta”)
    private String userId;
    @ApiModelProperty(example = “get criteria”)
    private String criteriaName;

    public String getUserId() {
    return userId;

    public void setUserId(String userId) {
    this.userId = userId;

    public String getCriteriaName() {
    return criteriaName;

    public void setCriteriaName(String criteriaName) {
    this.criteriaName = criteriaName;

    Here i want to avoid using ApiModelProperty() annotation for every variable and rather define a common property file and define these variables there and make swagger fetch variable values from that property file. How to do that?

  19. Shipra Jaiswal on

    can we use swagger if we will write this /* in web.xml.
    UI page is not loading when I am not providing prefix in url-pattern in servlet-mapping.

  20. sreeram sathyam on

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

  21. 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(
    at com.mangofactory.swagger.spring.ControllerAdapter.describeAsDocumentationEndpoint(
    at com.mangofactory.swagger.spring.DocumentationReader.addEndpointDocumentationIfMissing(
    at com.mangofactory.swagger.spring.DocumentationReader.processMethod(
    at com.mangofactory.swagger.spring.DocumentationReader.buildMappingDocuments(
    at com.mangofactory.swagger.spring.DocumentationReader.(
    at com.mangofactory.swagger.spring.controller.DocumentationController.setServletContext(
    … 71 more

Leave a Reply