Spring Boot - REST API Documentation using OpenAPI
Last Updated : 24 Apr, 2025
For any application, API documentation is essential for both users and developers. How to use an API, what will be the request body, and what will the API's response be? API documentation is the answer to all of these questions, springdoc-openapi is a Java library that automates the generation of the API documentation in both JSON/YAML and HTML format. In this article, we'll create a Spring boot application and use springdoc-openapi to document the REST APIs.
Setting up the Project
for this article, we'll be using openAPI 2.0.4 and Spring Boot 3.0.6. To have springdoc-openapi generate API documentation, add the below dependency to your pom.xml.
XML <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.0.2</version> </dependency>
If you don't have the validation dependency, you may face some errors; therefore, to avoid errors, include the below dependency if you don't have it.
XML <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
- Now, the documentation will be available in JSON format at http://localhost:8080/v3/api-docs
- The documentation will be available in YAML format at http://localhost:8080/v3/api-docs.yaml
- The swagger UI will be available at http://localhost:8080/swagger-ui.html
You can also customize the URL of the API documentation. Add the lines below to the application.properties file.
springdoc-swagger-ui.path=/swagger-ui.html springdoc.api-docs.path=/api-docs
Controller Class
Here we're creating an employee management application, and below are the REST APIs associated with it.
Java @RestController @RequestMapping("/employee") public class EmployeeController { @Autowired private Employee employeeService; @PostMapping("/addEmployee") public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee){ return ResponseEntity.ok(employeeService.saveEmployee(employee)); } @PutMapping("/updateEmployee") public ResponseEntity<Employee> updateEmployee(@RequestBody Employee employee){ return ResponseEntity.ok(employeeService.updateEmployee(employee)); } @DeleteMapping("/deleteEmployee/{id}") public ResponseEntity<Employee> deleteEmployee(@PathVariable int id){ return ResponseEntity.ok(employeeService.deleteEmployee(id)); } @GetMapping("/getEmployees") public ResponseEntity<List<Employee>> getEmployees(){ return ResponseEntity.ok(employeeService.getEmployees()); } }
After running the application navigate to http://localhost:8080/swagger-ui.html to view the swagger documentation.
Swagger-UI API documentation You can expand a particular API to look at it in detail. The request and response of the GET API look like
GET APISchema Validation Constraints Documentation
There may be several fields in a model class that requires validations. For this, we annotate the corresponding fields with JSR-303 bean validation annotations like @NotEmpty, @NotNull, @Size, @Min, @Max, etc. The springdoc-openapi automatically generates documentation for these validation constraints. Consider the Employee model class.
Java @Table @Entity public class Employee { @Id @Column @NotNull private int id; @Column @NotEmpty private String first_name; @Column private String last_name; @Column @Min(value = 18) @Max(value = 55) private int age; @Column @NotNull private double salary; }
The automatic generated for this Employee bean looks like
Validation constraints documentationResponse Codes Documentation
As you can see that there are a few response codes that are by default generated for us. For example, for a GET request, the documentation for response code 200 is already generated. But you can also document other response codes as well. To automatically generate documentation for response codes annotate the global exception handler class with @RestControllerAdvice annotation and annotate each exception handler method with @ResponseStatus annotation.
Java @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(EmployeeNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ResponseEntity<String> handleEmployeeNotFoundException(EmployeeNotFoundException employeeNotFoundException){ return new ResponseEntity<>(employeeNotFoundException.getMessage(), HttpStatus.NOT_FOUND); } @ExceptionHandler(EmployeeAlreadyExistsException.class) @ResponseStatus(HttpStatus.CONFLICT) public ResponseEntity<String> handleEmployeeAlreadyExistsException(EmployeeAlreadyExistsException employeeAlreadyExistsException){ return new ResponseEntity<>(employeeAlreadyExistsException.getMessage(),HttpStatus.CONFLICT); } }
The documentation generated looks like
Response codes documentationCustomizing API Documentation using @Operation and @ApiResponses
We can add some descriptions to our API by using @Operation and @ApiResponses annotations. We'll annotate the controller class with these annotations and customize the API description.
Java @Operation(summary = "Delete an employee by its id") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted an employee", content = {@Content(mediaType = "application/json",schema = @Schema(implementation = Employee.class))}), @ApiResponse(responseCode = "401",description = "Unauthorized user",content = @Content), @ApiResponse(responseCode = "404",description = "Employee not found",content = @Content), @ApiResponse(responseCode = "400",description = "Invalid employee id",content = @Content)}) @DeleteMapping("/deleteEmployee/{id}") public ResponseEntity<Employee> deleteEmployee(@PathVariable int id){ return ResponseEntity.ok(employeeService.deleteEmployee(id)); }
After running the application, the documentation looks like
Customized delete APIConclusion
In this article, we have learned how to document the REST APIs using Spring Boot 3 and Springdoc Open API. At the start, we learned how to set up a project for a particular use case. Then we saw how we could customize the documentation URL. Then we saw how documentation for schema validation constraints is generated for us. Then, we saw how we can document response codes. In the end, we saw how to use @Operation and @ApiResponses annotations to add descriptions to the APIs.
Similar Reads
Easiest Way to Create REST API using Spring Boot
Spring Boot is a powerful framework that makes it easy to create RESTful APIs. Creating a REST API using Spring Boot is one of the fastest and simplest ways to develop scalable and production-ready web services. Spring Boot simplifies REST API development by providing built-in features such as autom
11 min read
How to Create a REST API using Java Spring Boot?
Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
Streamlining API Documentation Using Postman
APIs (Application Programming Interfaces) are the backbone of interconnected software, enabling different applications to work together. As developers build more APIs, the need for clear and accessible documentation becomes more important. Good documentation ensures that others can easily understand
5 min read
JSON using Jackson in REST API Implementation with Spring Boot
When we build REST APIs with Spring Boot, we need to exclude NULL values from the JSON responses. This is useful when we want to optimize the data being transferred, making the response more compact and easier to process for the client. In this article, we are going to learn the approach that is use
4 min read
Spring Boot API Call using OkHttp
OkHttp is pretty smart when it comes to dealing with tricky network situations. It quietly bounces back from common connection hiccups and even tries different addresses if the first attempt doesn't work. This becomes crucial when you're dealing with situations that use both IPv4 and IPv6 or when yo
5 min read
Spring Boot - CRUD Operations Using Redis Database
Redis is an in-memory data structure that is used for faster access to data. It is used to store data that needs to be accessed frequently and fast. It is not used for storing large amounts of data. If you want to store and retrieve large amounts of data you need to use a traditional database such a
8 min read
How to generate API documentation using Postman?
Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge between two software applications which enables them to communicate and share data. In this article, you will learn how to generate API
2 min read
Spring MVC - Getting Cryptocurrency Details using REST API
Cryptocurrencies are a hot topic throughout the world. Trading with cryptocurrency got both pros and cons. Nowadays REST APIs are very useful to get much information including cryptocurrencies. In this article, we are going to see about one such REST API call to get cryptocurrency detail. We are goi
5 min read
Spring Boot â Building REST APIs with HATEOAS
In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions th
5 min read
Implementing Secure API Communication in Spring Boot
In modern web applications, securing API communication is important to protect sensitive data and ensuring the integrity of interactions between clients and servers. In this article, we will learn how to implement secure API communication in a Spring Boot application. Securing API communication is c
5 min read