In the previous post, we added validations to our application. With that, we brought it quite close to a production-level application. However, one of the important aspects of any application is documentation. In the context of REST API, documentation becomes even more important. A good documentation can increase the adoption of an API. A bad one can only lead to unpopularity. In this post, we will look at setting up Swagger with Spring Boot Application and see it in action.

Swagger is a framework or tool that brings much-needed automation to the task of documenting APIs. Swagger tools perform the hard-work of keeping your API documentation up-to date. It also provides built-in solutions to visualize an API. In other words, it is an essential part of building production-grade Spring Boot Microservices.

If you are not aware about Swagger, you can read more about it on the official Swagger site.

The Dependencies

We will be using the Springfox implementation of Swagger. This implementation helps bringing the capabilities of Swagger to a Spring Boot application in a seamless manner.

To achieve this, we will be adding another dependency to our Spring Boot starter project.

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>

Setting up Swagger with Spring Boot

The configuration for Swagger is minimal. It centers around the Docket bean. We need to add the below configuration in a configuration class.

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

Some of the important points in the above piece of code are:

  • The @EnableSwagger2 annotation is used to enable Swagger for this application.
  • We create a Docket bean and annotate it with @Bean.
  • The Docket bean’s select() method returns an instance of ApiSelectorBuilder. Basically, this allows a way to control the end-points that are exposed by Swagger.
  • Request Handlers can be configured using RequestHandlerSelectors and PathSelectors. However, using any() for both the options will enable the entire API to be available for Swagger.
  • We annotate the overall class with @Configuration. Basically, this tells Spring to scan this class and wire up the bean in the context.

This configuration is enough to enable Swagger with Spring Boot application. We can verify it now.

To do so, start the application and visit the URL http://localhost:8080/v2/api-docs.

We should see a JSON response as in the below screenshot:

swagger with spring boot
swagger with spring boot

As you can see, this JSON schema is basically just defining our API end-points. Basically, this is a machine-readable representation of all the REST end-points that are getting exposed from our application.

Swagger UI

The JSON representation of our APIs is incredibly useful. However, it is so much more easy for others to view our API documentation in a nice graphical user interface.

Swagger UI makes this possible. It also adds support for calling the APIs and playing around with their capabilities.

Dependencies

To enable Swagger UI, we need to add another dependency to our POM.xml. This dependency is called springfox-swagger-ui.

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.2</version>
</dependency>

Testing the UI

Just by adding this dependency, the Swagger documentation for our API will be exposed via a nice user-interface.

To see it in action, we can restart the application and visit http://localhost:8080/swagger-ui.html.

swagger ui with spring boot

As you can see, we see a bunch of controllers visible on the page that opened. The ones that we have declared as a developer are the vehicle-command-controller and the vehicle-query-controller.

When we click on these controllers in the UI, we can also see the methods and the resources exposed in a particular controller. For example, the vehicle-command-controller has POST and PUT methods.

Similarly, vehicle-query-controller has two GET methods. One to fetch a list of vehicles and the other to get the data for a single vehicle.

The others (such as operation-handler and web-mvc-links-handler) are wired up by Spring Boot itself.

Filtering APIs for Swagger

The Docket bean that we created earlier can also be configured to provide more fine-grained control over the API documentation.

Most of the time, we want to restrict the APIs exposed on the Swagger. We don’t want all the infrastructure related end-points as part of the Swagger schema.

To do so, RequestHandlerSelector provides us options to filter APIs based on base-package, class annotations or method annotations.

PathSelectors can provide additional filtering based on the request paths. We can see these two options in action below:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.progressivecoder.demo.springbootstarter.controllers"))
                .paths(PathSelectors.ant("/api/*"))
                .build();
    }
}

In the RequestHandlerSelectors.basePackage(), we specify the package where we have declared our controllers. Swagger only picks up controllers declared in this package.

Also, using PathSelectors.ant(), we specify that only paths starting with /api should be picked up.

Due to the above filter, now the Swagger UI for our application will show only two controllers that satisfy the above filtering conditions.

swagger ui with spring boot

Conclusion

Swagger UI is a great way to document our APIs. Also, due to the Spring Fox implementation it works seamlessly with Spring Boot using minimal Java configuration.

However, there are quite a few more customization options available at our disposal. We will look at advanced Swagger configuration options in the subsequent post.

The code till this point is available on Github.


Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *