Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaSpring Boot – REST API Documentation using OpenAPI

Spring Boot – REST API Documentation using OpenAPI

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

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 API

GET API

Schema 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 documentation

Validation constraints documentation

Response 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 documentation

Response codes documentation

Customizing 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 API

Customized delete API

Conclusion

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.

RELATED ARTICLES

Most Popular

Recent Comments