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

Spring Framework 5
Become a Spring Framework Guru with my Spring Framework 5: Beginner to Guru Online Course!

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

There are some breaking changes in Spring Boot 2 with Swagger 2 which affect the auto configuration of Swagger UI. To configure support for Swagger UI with Spring Boot 2, you need to extend the class WebMvcConfigurationSupport and add two resource handlers.

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.

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.

Spring Framework 5
Learn Spring Framework 5 with my Spring Framework 5: Beginner to Guru course!

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.

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.


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.

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.

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

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

  15. Sounds PERFECT, here at Brazil when we say “você é o cara”, it means you are the man, thank you very much. Aloha brother from 0s and 1s!

  16. Nice tutorial..
    Can you help me to configure authentication part too?
    My application first generate token with the authentication Rest API then I want to pass that token in the header while calling all other API’s.

  17. After successfully importing the project i’m not able to see the swagger-ui.html i.e its not list all the api’s. But i’m able to see the json format..anyhting im missing over here

    • if Swagger is behind any auth, you need to do following in SpringBoot Security
      http.authorizeRequests().antMatchers(“/swagger-resources/**”).permitAll().anyRequest().fullyAuthenticated();

  18. Hi there ,
    I am doing exactly the same but in the expression of regex , its giving me complie time error of “cannot access Predicate” .

    Can you help where and what i am doing wrong .

    public Docket docket(){
    return new Docket(DocumentationType.SWAGGER_2)
    .select()
    .apis(RequestHandlerSelectors.basePackage(“com.r4cloud.controller”))
    .paths(regex(“/cerberus.*”))
    .build()
    .apiInfo(metaData());

    }

    • update your code like this….
      public Docket docket(){
      return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.basePackage(“com.r4cloud.controller”))
      .paths(pathbuilders.regex(“/cerberus.*”))
      .build()
      .apiInfo(metaData());

      }

  19. Hi,
    I am using swagger2 and spring boot application. I configured swagger exactly the way you showed..but when i try to hit that endpoint it says
    “No mapping found for HTTP request with URI [/example/api/swagger-ui.html] in DispatcherServlet with name ‘dispatcherServlet’

    Here is my controller:
    @SuppressWarnings(“unchecked”)
    @PostMapping(value = “/example”, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)

    public ResponseEntity postMatchedMembers(
    @ApiParam(value = “Request body “, required = true, allowMultiple = true) @Valid @RequestBody Request DataRequest,
    BindingResult result) throws Exception{

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    List exampleList;

    SwaggerConfig.java:
    @Configuration
    @EnableSwagger2

    public class SwaggerConfig {

    @Bean
    public Docket matchingPersistenceApi() {
    return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(“com.hms.matching.postmatch.controller”))
    .paths(PathSelectors.ant(“/**”)).build().apiInfo(metaData());
    }

    My Boot.java
    @SpringBootApplication
    @ComponentScan(“com.example”)
    @EnableJpaRepositories(“com.example.dao”)
    @EntityScan(“com.example.domain”)
    @EnableAsync
    @EnableTransactionManagement
    public class ExampleApiApplication {

    public static void main(String[] args) {
    SpringApplication.run(Example.class, args);
    }

    It used to work earlier..i dont know what went wrong suddenly it stopped working. Please help me find what the issue could be? TIA

    • Did you change something? Try doing a clean & rebuilding.

  20. This is great Jason, Not Yaml? are there easy change to output Yaml?

  21. Fantastic Tutorial. As always Guru is Guru. Perfect for any newbie. Thanks

  22. Tried running your tutorial. Had problems with Springfox dependencies 2.6.1…works after changing the Springfox dependencies to 2.8.

    • The post has been updated to Spring Boot 2.0.0.0 RELEASE

  23. Can you create a post on Swagger definition through JSON and YAML files.

  24. With Spring Boot 2.0.1.RELEASE I had the problem, that some of my configuration in my application.properties ware not taken (for example spring.jackson.serialization.write-dates-as-timestamps=false )

    Sollution is:
    SwaggerConfig should NOT extend from WebMvcConfigurationSupport. Also you don’t need to add the overridden method addResourceHandlers()

  25. Very helpful post.I like your post.Thanks!!!
    https://www.ai1tutorial.com/spring-restwithswagger/

  26. You should very much consider creating a proper RESTful uri structure that is resource (noun) oriented. There is no reason to have /products[/add/show/update/delete]. The http verb (hwich you’re using properly) defines what the operation on the resource is, including it in the URI is unnecessary and definitely not a best practice.

  27. Nice Tutorial

  28. Hello, Guru John. I really enjoyed and benefited from the article. Now I can make sense of this Spring Boot 2 code I’m looking at. (Although it doesn’t define productApi inside a class derived from WebMvcConfigurationSupport.)

    Now I’d like to read about Swagger Editor and Swagger Codegen. Did you never get around to writing blog posts on those items? Do you have any ideas where a nice, readable article might be?

    Regards, Rick

  29. Great tutorial!!, But I have a problem: I devel a simple Spring Boot Domain with only one object, everything is Ok in localhost when deploy my App: http://localhost:3000/swagger-ui.html

    But now I deploy the same App in Pivotal WebService (Paas), my model runs Ok, but when I go to: https://trainingcfservices.cfapps.io/swagger-ui.html I obtain a error at button of paig where I must see my controler with a red ERROR button, when click I obtain this message in my brower!. The App runs Ok of course, but the Swagger documentation not works oK in Pivotal and yes in my local computer

    {“messages”:[“attribute paths is missing”],”schemaValidationMessages”:[{“level”:”error”,”domain”:”validation”,”keyword”:”required”,”message”:”object has missing required properties ([\”paths\”])”,”schema”:{“loadingURI”:”#”,”pointer”:””},”instance”:{“pointer”:””}}]}

    What is the possible error?

    Regards

    • Resolve the problem desable the swagger validation with this bean inside Swagger configuration

      @Bean
      UiConfiguration uiConfig() {
      return UiConfigurationBuilder.builder()
      .displayRequestDuration(true)
      .validatorUrl(“”)
      .build();
      }

Leave a Reply