Configuring Swagger 2 with Spring Boot for RESTful API Documentation

1. Introduction

Mathuragini Thiyaneswaran
3 min readNov 10, 2020

For all the web applications, front-end and back-end components often separated. Usually, we expose APIs as a back-end component for the front-end component or third-party app integrations.

In case, it is essential to have proper API specifications for the back-end needed. At the same time, the API documentation should be informative, readable, and easy to follow.

2. Create your Project

I develop a small project Library Management, and here is the Project Structure. This Contains a controller for the sample demo.

Have the facility to ADD, LIST, VIEW, UPDATE book details.

My Project Folder Structure

3. Adding Maven dependency

First, need to install the libraries in pom.xml: I used the Spring boot 2.2.4 version on my application. Swagger 2, all the version not support. I have tested all the versions, given below version swagger2 version support to my project.

You have to pick the swagger version along with your Spring boot version.

Add maven dependency in pom.xml

4. Configuring Swagger 2 in the Application

Create a package config and configure the swagger in SwaggerConfig.java class, as given below.

Configure Swagger 2 in the application

In this configuration class, the @EnableSwagger2 annotation enables Swagger's 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.

The regex parameter passed to paths() acts as an additional filter to generate documentation only for the path starting with “/.*”.

At this point, you should be able to test the configuration by starting the app and pointing your browser to

http://localhost:8085/library/v2/api-docs

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

We can see that Springfox has generated the specifications for the Book entity with HTTP methods like GET ( Get all and Get by ID), POST, PUT, and DELETE.

Sample testing for GET all API,

Get all API Specifications.

--

--