Home » Integration » Use Swagger to document REST APIs in Spring Boot App

Use Swagger to document REST APIs in Spring Boot App

This article explains how to use swagger in Spring Boot applications to document the REST APIs. Here let us see the below things one by one regarding the swagger implementation in spring boot.

  • What is Swagger?.
  • Why do we need Swagger?.
  • Why do we need to document REST APIs?.
  • Use Swagger in Spring Boot Application to document REST APIs.

What is Swagger?

Swagger is a collection of open-source tools built around the OpenAPI specifications. We can use swagger to design, build, consume and document the REST API.

There are many open-source tools that swagger has. Those are Swagger Editor, Swagger UI, Swagger Codegen. Here let us use Swagger UI to see the documented API.

Why do we need Swagger?

As I said above swagger is used to design, build, consume and document the REST API. But the main purpose of using swagger is to document the REST API.

Here also let us use swagger to document the REST API in spring boot applications.

Why do we need to document REST APIs?

For example, you are an API developer and you have developed the different REST API with different logic for your application. If you want to consume that API from different clients like Web UI or Mobile app then you need documentation for all the APIs that you have developed right.

In case if you may not know the UI development since you are an API developer then the other person has to work for developing the UI for your application. In this situation how does the other person know the API that he has to consume right? For that, we have to do the documentation for all the APIs.

If we are having the best documentation for the backend REST APIs then any other developers can consume that APIs with the help of that document. It's easy for them to do the development quickly.

We can create the document for the APIs manually or automatically. If manually means we need to update the document manually whenever the changes happen in the REST APIs. We can handle the document by own or we need a resource to handle the documentation.

If automatically means we don't need to manually update the document. It updates automatically whenever the changes in APIs. We don't need any resources to handle the documentation, the API developer itself is enough to handle the documentation.

Here the Swagger comes into the picture. Swagger is the best tool for documenting the REST APIs automatically. Once we configured Swagger in our application then we don't worry about the API documentation and all. Swagger will take care of everything for us. The only thing we need to configure and customize the Swagger in our application.

Integrate Swagger with Spring Boot Application to document REST API

Now let us start to integrate Swagger in the Spring Boot Application. First, we need a Spring Boot Application with the REST APIs. We already created the Spring Boot Application with basic CRUD operations of MongoDB in this article Spring MongoDB Basic CRUD.

We use that same project here from the above link to integrate Swagger. The below controller class with REST endpoints and Model objects from that project.

Controller Class (ProfileController)

package com.tipstocode.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.tipstocode.manager.ProfileManager;
import com.tipstocode.model.ProfileVO;

@RestController
@RequestMapping("/api")
public class ProfileController {	
	
	@Autowired
	ProfileManager userManager;
	
	@RequestMapping(value = "/saveprofile", method = RequestMethod.POST )
	public ResponseEntity<ProfileVO> saveUser(@RequestBody ProfileVO userVO) {		
		userVO = userManager.saveUser(userVO);		
		return new ResponseEntity<ProfileVO>(userVO, HttpStatus.OK);		
	}	
	@RequestMapping(value = "/getprofilebyid", method = RequestMethod.GET )	
	public ResponseEntity<ProfileVO> getUserById(@RequestParam("id") String id) {		
		ProfileVO userVO = userManager.getUserById(id);		
		return new ResponseEntity<ProfileVO>(userVO, HttpStatus.OK);		
	}	
	@RequestMapping(value = "/updateprofile", method = RequestMethod.POST )
	public ResponseEntity<ProfileVO> updateUser(@RequestBody ProfileVO userVO) {		
		userVO = userManager.updateUser(userVO);		
		return new ResponseEntity<ProfileVO>(userVO, HttpStatus.OK);		
	}	
	@RequestMapping(value = "/deleteprofilebyid", method = RequestMethod.GET )
	public ResponseEntity<Long> deleteUserById(@RequestParam("id") String id) {		
		long count = userManager.deleteUserById(id);		
		return ResponseEntity.ok(count);			
	}		
}

Model Object - ProfileVO serialized with MongoDB collection user_profile.

package com.tipstocode.model;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection  = "user_profile")
public class ProfileVO {	
	@Id	
	private ObjectId _id;	
	private String firstName;	
	private String lastName;	
	private String mobile;	
	private String emailId;	
	public ObjectId get_id() {
		return _id;
	}
	public void set_id(ObjectId _id) {
		this._id = _id;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getEmailId() {
		return emailId;
	}
	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}
}

Please do the below things to implement swagger in Spring Boot Application.

  1. First, we have to add the Swagger dependency for Spring Boot Application named SpringFox.
  2. Enable Swagger in Spring Boot Application.
  3. Add Swagger UI dependency to see the documented APIs in a browser.

Add Swagger dependency in Spring Boot Application

Let us add the below swagger dependency in the pom.xml file like below.

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

Enable Swagger in Spring Boot Application

To enable Swagger in Spring Boot, we have to create a separate config file like below.

package com.tipstocode.SpringMongo;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SpringSwaggerConfig {    
}

The annotation @EnableSwagger2 enables the Swagger in Spring Boot Application. Now we have successfully enabled the swagger in Spring Boot Application. Let's run the application and check the below URL in the postman.

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

The above URL displays all the documented APIs in JSON format in Postman like below.

Swagger-API-Documentation-URL-JSON

The above JSON format documented APIs is not easily readable by the users. For this, the swagger provides a tool called Swagger UI that provides the separate endpoint (URL) to see the documented APIs elegantly.

Add Swagger UI dependency in Spring Boot Application

Let's add the below dependency in the pom.xml file

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

That's it. Now check this URL in the browser to see the documented APIs with a good look.

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

Swagger-UI-URL-Documented-APIs

The above URL shows the documented REST APIs in the ProfileController. Not only that, it shows some other endpoints like basic-error-controller, operation-handler, and web-mvc-links-handler. The model section also displays all the model objects of Spring MVC.

Generally, the Swagger UI documented not only the REST endpoints created by us but it documents all the endpoints and model objects from the Spring MVC configuration.

If you look into the top section then it displays its own title like 'Api Documentation', description, version, terms of use, and contact information.

If you want to avoid documenting the APIs and model objects from the out-of-box Spring Configuration and put your own title, description and etc then we have to customize the Swagger based on our need.

Let us see how to customize the swagger to avoid documenting unwanted things and use more annotations to provide more and more information to the documented APIs in the next article. Thanks!. Keep Reading!.

Leave a Reply

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