Spring Boot RESTful API Documentation with Swagger 2

Spring Boot makes developing RESTful services ridiculously easy. And using Swagger makes documenting your RESTful services easy.

Building a back-end API layer introduces a whole new area of challenges that goes beyond implementing just endpoints. You now have clients which will now be using your API. Your clients will need to know how to interact with your API. In SOAP based web services, you had a WSDL to work with. This gave API developers a XML based contract, which defined the API. However, with RESTFul web services, there is no WSDL. Thus your API documentation becomes more critical.

API documentation should be structured so that it’s informative, succinct, and easy to read. But best practices on, how you document your API, its structure, what to include and what not to is altogether a different subject that I won’t be covering here. For best practices on documentation, I suggest going through this presentation of Andy Wikinson.

In this post I’ll cover how to use Swagger 2 to generate REST API documentation for a Spring Boot project.

Swagger 2 in Spring Boot

Swagger 2 is an open source project used to describe and document RESTful APIs. Swagger 2 is language-agnostic and is extensible into new technologies and protocols beyond HTTP. The current version defines a set HTML, JavaScript, and CSS assets to dynamically generate documentation from a Swagger-compliant API. These files are bundled by the Swagger UI project to display the API on browser. Besides rendering documentation, Swagger UI allows other API developers or consumers to interact with the API’s resources without having any of the implementation logic in place.

The Swagger 2 specification, which is known as OpenAPI specification has several implementations. Currently, Springfox that has replaced Swagger-SpringMVC (Swagger 1.2 and older) is popular for Spring Boot applications. Springfox supports both Swagger 1.2 and 2.0.

We will be using Springfox in our project.

To bring it in, we need the following dependency declaration in our Maven POM.

In addition to Sprinfox, we also require Swagger UI. The code to include Swagger UI is this.

Free Spring TutorialThe Spring Boot RESTful Application

Our application implements a set of REST endpoints to manage products. We have a Product JPA entity and a repository named ProductRepository that extends CrudRepository to perform CRUD operations on products against an in-memory H2 database.

The service layer is composed of a ProductService interface and a ProductServiceImpl implementation class.

The Maven POM of the application is this.

pom.xml

The controller of the application , ProductController defines the REST API endpoints. The code of ProductController is this.

In this controller, the @RestController annotation introduced in Spring 4.0 marks ProductController as a REST API controller. Under the hood, @RestController works as a convenient annotation to annotate the class with the @Controller and @ResponseBody.

The @RequestMapping class-level annotation maps requests to /product onto the ProductController class. The method-level @RequestMapping annotations maps web requests to the handler methods of the controller.

Configuring Swagger 2 in the Application

For our application, we will create a Docket bean in a Spring Boot configuration to configure Swagger 2 for the application. A Springfox Docket instance provides the primary API configuration with sensible defaults and convenience methods for configuration. Our Spring Boot configuration class, SwaggerConfig is this.

In this configuration class, the @EnableSwagger2 annotation enables Swagger support in the class. The select() method called on the Docket bean instance returns an ApiSelectorBuilder, which provides the apis() and paths() methods to filter the controllers and methods being documented using String predicates. In the code, the RequestHandlerSelectors.basePackage predicate matches the guru.springframework.controllers base package to filter the API. The regex parameter passed to paths() acts as an additional filter to generate documentation only for the path starting with /product.

At this point, you should be able to test the configuration by starting the app and pointing your browser to http://localhost:8080/v2/api-docs
Swagger JSON Output
Obviously, the above JSON dump that Swagger 2 generates for our endpoints is not something we want.

What we want is some nice human readable structured documentation, and this is where Swagger UI takes over.

On pointing your browser to http://localhost:8080/swagger-ui.html, you will see the generated documentation rendered by Swagger UI, like this.

Swagger default documentation

As you can see, Swagger 2 used sensible defaults to generate documentation of our ProductController .

Then Swagger UI wrapped everything up to provide us an intuitive UI. This was all done automatically. We did not write any code or other documentation to support Swagger.

Customizing Swagger

So far, we’ve been looking at Swagger documentation, as it comes out of the box. But Swagger 2 has some great customization options.

Let’s start customizing Swagger by providing information about our API in the SwaggerConfig class like this.

SwaggerConfig.java

In the SwaggerConfig class, we have added a metaData() method that returns and ApiInfo object initialized with information about our API. Line 23 initializes the Docket with the new information.

The Swagger 2 generated documentation, now look similar to this.
Swagger Generated API Information

Swagger 2 Annotations for REST Endpoints

At this point, if you click the product-controller link, Swagger-UI will display the documentation of our operation endpoints, like this.
Swagger default endpoint documentation

We can use the @Api annotation on our ProductController class to describe our API.

The Swagger-UI generated documentation will reflect the description, and now looks like this.
Customized Swagger Generated API Description
For each of our operation endpoint, we can use the @ApiOperation annotation to describe the endpoint and its response type, like this:

Swagger 2 also allows overriding the default response messages of HTTP methods. You can use the @ApiResponse annotation to document other responses, in addition to the regular HTTP 200 OK, like this.

One undocumented thing that took quite some of my time was related to the value of Response Content Type. Swagger 2 generated "*/*", while I was expecting "application/json" for Response Content Type. It was only after updating the @RequestMapping annotation with produces = "application/json" that the desired value got generated. The annotated ProductController is this.

ProductController.java

The output of the operation endpoints on the browser is this.
Swagger generated endpoint and response code documentation
If you have noticed, the current documentation is missing one thing – documentation of the Product JPA entity. We will generate documentation for our model next.

Swagger 2 Annotations for Model

You can use the @ApiModelProperty annotation to describe the properties of the Product model. With @ApiModelProperty, you can also document a property as required.

The code of our Product class is this.

Product.java

The Swagger 2 generated documentation for Product is this.
Swagger model documentation

Summary

Beside REST API documentation and presentation with Swagger Core and Swagger UI, Swagger 2 has a whole lot of other uses too that is beyond the scope of this post. One of my favorite is Swagger Editor, a tool to design new APIs or edit existing ones. The editor visually renders your Swagger definition and provides real time error-feedback. Another one is Swagger Codegen – a code generation framework for building Client SDKs, servers, and documentation from Swagger definitions.

Swagger 2 also supports Swagger definition through JSON and YAML files. It is something you should try if you want to avoid implementation-specific code in your codebase by externalizing them in JSON and YAML files – something that I will cover in a future post.

The code for this post is available for download here.

Share

You May Also Like

18 comments on “Spring Boot RESTful API Documentation with Swagger 2

  1. Nice tutorial I really learn a lot. Please can you do a tutorial that has an Oauth2 setup with swagger?

  2. Thanks for this tutorial it was very useful for me. GL

  3. Nice tutorial! Has anyone managed to run the example?

  4. Very Nice and clear tutorial. Thanx

  5. These are the required webjars by the way: https://mvnrepository.com/artifact/org.webjars/swagger-ui

  6. Thank you, this is a very useful tutorial, I used this to implement documentation on my API. Kudos!

  7. HI !

    Your tutorial is very nice!

    There seems to be an issue with “@Api”, which look like more or less deprecated
    @Api(value=”onlinestore”, description=”Operations pertaining to products in Online Store”)

    They seem to recommend using @SwaggerDefinition instead, but I couldn’t have it work with a Spring boot @RepositoryRestResource 🙁

    Any idea?

    Thanks!
    Cyril

  8. I am able to get the ui and previously it was showing the documentation. But Right now, it stopped accessing the controllers from the swagger documentation. Any idea why my controller definnition has not been picked up which was picking up before few days. I can assure that there were no changes on my controller side. BTW I am using sprint boot with RestController.

  9. Also, when I hit /v2/api-docs, I don’t see json containing my application specific data except some common data like apache license and application context.

  10. Sometimes, you need to answer when someone is asking for help.

  11. Very Informative 🙂

  12. HI thanks for this tutorial. I have one doubt if i want to add more paths can I do that as my controllers are starting from diffrent paths

    • Couldn’t get you. Do you mean documentation of multiple controllers? If so, Yes! Use @RequestMapping at controller class level. For example, I’ll use this for a new controller handling recommendations

      @RestController
      @RequestMapping(“/recommendation”)
      @Api(value=”onlinestore”, description=”Operations pertaining to product recommendation in Online Store”)
      public class RecommendationController{ … }

      Swagger will list both controllers.

  13. I love this tutorial, and we’re using it here at the NFL.
    Unfortunately, some of our microservices are not accepting this. Most likely due to some conflict with @IntegrationTest.

    I started an issue on their github page. If anyone can help, we would greatly appreciate it.
    https://github.com/springfox/springfox/issues/1894

  14. good one tom!!

Leave a Reply