Add Swagger 2 to Rest API

Mercy Jemosop
3 min readSep 28, 2021

Display your spring-boot endpoints in the browser

Introduction

Swagger 2 provides the API documentation which are informative, readable, and easy to follow. It uses Springfox implementation of the Swagger 2 specification.

Swagger 2 makes it easy for the front-end and back-end team to collaborate since it exposes the necessary details eg. endpoint, variables used etc. This is important in avoiding conflict.

This is what we are creating. The product controller is the name of my controller class with 4 endpoints/controller functions.

To check the content of a controller e.g parameters/variables used just click on one. I will use the login example.

N.B the functions do not display the correct login function or method it is just for demo purposes.

Swagger2 allows you to view the data types on the right side and you can also try to test with your values. When you click on the try out button, below image will be your sample output. For my case it failed but if you had the correct functions and add the correct parameters you will get the 200 or 201 status.

Here is a sample of my controller.

As you can see, swagger2 gets your endpoints and its required parameter automatically. Hope that is a bit clear

Set up

Add the swagger dependencies to your pom.xml. Check the latest version. N.B some version may have problems when displaying the documentation soln:

  • build your application
  • change swagger dependency versions
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>

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

Create a config folder or just a file to hold your swagger config file e.g SwaggerConfig.java

In the file above you need to edit one part, the base package name. Here is an image of my base package name to guide you

apis(RequestHandlerSelectors.basePackage("com.tables.Tables"))

N.B if you have restricted/authenticated your endpoints you need to permit swagger endpoint for it to work or else you will get 403.

That is all you need, run your application. To access swagger you can paste the following endpoints on your browser and change where necessary.

http://localhost:8080/v2/api-docs

http://localhost:8080/swagger-ui.html

Here is a tutorial on swagger if the instructions are not clear

Happy Coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

--

--

Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy