Hey guys in this post, we will discuss documenting the Spring Boot REST APIs using Swagger Open API 3 with Example
Table of Contents
Overview
The OpenAPI Specification, originally known as the Swagger Specification, is a specification for machine-readable interface files for describing, producing, consuming, and visualizing RESTful web services.
Complete example
Let’s create a step-by-step spring boot project and add swagger to the project to document REST APIs.
Read More:
- Check the complete Spring Boot Data JPA Tutorials
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:schemaLocation="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>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.9</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(). springdoc-openapi-ui
dependency is for swagger Open API 3.
Configure the datasource
Open application.properties
and add the following contents
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);
}
}
That’s it. Now spring boot will take care of documenting the APIs using swagger Open API 3.
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
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.