Swagger API Documentation Example Spring Boot





Hey guys in this post, we will discuss adding API documentation for the Spring Boot application using Swagger.

Overview


Swagger is an Interface Description Language for describing RESTful APIs expressed using JSON. Swagger is used together with a set of open-source software tools to design, build, document, and use RESTful web services. Swagger includes automated documentation, code generation, and test-case generation.

Swagger provides a UI to see all the APIs available in the application. We can check each API request and response. Also, it provides an option to test out the APIs on the go.

Complete example


Let’s create a step-by-step spring boot project and add swagger to the project to document REST APIs.

Read More:

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocationa="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>springdatajpa</artifactId>
	<version>v1</version>
	<name>springdatajpa</name>
	<description>Spring data jpa</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container.




spring-boot-devtools dependency for automatic reloads or live reload of applications. spring-boot-starter-data-jpa dependency is a starter for using Spring Data JPA with Hibernate. lombok dependency is a java library that will reduce the boilerplate code that we usually write inside every entity class like setters, getters, and toString(). springfox-swagger2 and springfox-swagger-ui dependencies for swagger API documentation.

Make sure that swagger dependencies both should be having same version

Configure the datasource


spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=scbushan05
spring.datasource.password=scbushan05

spring.jpa.hibernate.ddl-auto=update

Create an entity class


Create Employee.java inside the in.bushansirgur.springboot.entity package and add the following content

package in.bushansirgur.springboot.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Entity
@Table(name = "tbl_employee")
@Setter
@Getter
@NoArgsConstructor
public class Employee {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	
	private String name;
	
	private String location;
	
	
}
  • @Data annotation which is a Lombok annotation, that will automatically create setters, getters, toString(), and equals() for us.
  • @Entity is a mandatory annotation that indicates that this class is a JPA entity and is mapped with a database table.
  • @Table annotation is an optional annotation that contains the table info like table name.




  • @Id annotation is a mandatory annotation that marks a field as the primary key

Create a Repository


Create EmployeeRepository.java inside the in.bushansirgur.springboot.repository package and add the following content

package in.bushansirgur.springboot.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import in.bushansirgur.springboot.entity.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {

}

Create a Rest controller


Create EmployeeController.java inside the in.bushansirgur.springboot.controller package and add the following content

package in.bushansirgur.springboot.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import in.bushansirgur.springboot.entity.Employee;
import in.bushansirgur.springboot.repository.EmployeeRepository;

@RestController
public class EmployeeController {
	
	
	@Autowired      
	private EmployeeRepository eRepo;
	
	@PostMapping("/employees")
	public Employee save (@RequestBody Employee employee) {
		return eRepo.save(employee);
	}
	
	@GetMapping("/employees")
	public List<Employee> get () {
		return eRepo.findAll();
	}
	
	@GetMapping("/employees/{id}")
	public Employee get (@PathVariable Long id) {
		Optional<Employee> employee = eRepo.findById(id);
		if (employee.isPresent()) {
			return employee.get();
		}
		throw new RuntimeException("Not found for the id "+id);
	}
	
	@PutMapping("/employees/{id}")
	public Employee update (@PathVariable Long id, @RequestBody Employee employee) {
		employee.setId(id);
		return eRepo.save(employee);
	}
	
	@DeleteMapping("/employees/{id}")
	public ResponseEntity<HttpStatus> delete (@PathVariable Long id) {
		eRepo.deleteById(id);
		return new ResponseEntity<HttpStatus>(HttpStatus.NO_CONTENT);
	}
}

Enable Swagger


Inside the main class, SpringdatajpaApplication.java enables the swagger by adding annotation @EnableSwagger2 to the class.

package in.bushansirgur.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class SpringdatajpaApplication {

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

}

That’s it. Now spring boot will take care of documenting the APIs using swagger.

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the browser and enter the following URL –

  • localhost:8080/swagger-ui.html

Screenshot-2021-06-26-at-9-12-16-AM

That’s it for this post. I hope you enjoyed this post, if you did then please share this with your friends and colleagues. Also, you can share this post with your social media profiles. Thank you I will see you in the next post.



About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

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