Document Spring REST API with OpenAPI 3(Swagger)

Documenting API is an essential part of the real-world project where we have multiple teams from microservices to the frontend side all transfer data through REST API. So well and clear API documentation will save us a lot of time in the development process.

In 2017, Open API Initiative released OpenAPI Specification 3.0.0 which includes notable enhancements compared to Swagger 2 but we don’t deep dive into specific detail here.

In this tutorial, we will look at springdoc-openapi a Java library that helps automate the generation of API documentation in Spring Boot projects with OpenAPI3 specification.

1. Add the springdoc-openapi Dependency

To enable the generation of API documentation, we need to add a springdoc-openapi-ui dependency to our Spring Boot project.
You can check out the latest version through this mvnrepository link https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-ui.

Maven dependency

<dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>1.6.13</version>
</dependency>

Gradle dependency

implementation 'org.springdoc:springdoc-openapi-ui:1.6.13'

This will enable swagger-ui and many features in your Spring Boot application without any additional configuration.

2. View Documentation in Swagger UI

Let’s create a simple StudentController as follows.

@RestController
@RequestMapping("/students")
public class StudentController {

    @GetMapping
    public List<Student> getListStudent() {return Collections.emptyList();}

    @PostMapping
    public void addStudent(Student student){}

    @PutMapping
    public void updateStudent(Student student){}

    @DeleteMapping
    public void deleteStudent(){}
}

Just start your spring-boot project and open the following URL to see the Swagger UI.

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

We can see that all methods defined in StudentController class have been visualized with path, HTTP method, and param… besides you can try consuming API endpoints with the Try it out button.

Request

Response

For custom HTML swagger-ui, add this custom springdoc property in your spring-boot config file(application.properties or application.yml).

# swagger-ui custom path
springdoc.swagger-ui.path=/swagger-ui.html

3. Conclusion

I hope this tutorial was helpful to you. It demonstrates how to enable OpenAPI documentation for your Spring Boot application and how to view this documentation in Swagger UI. The springdoc-openapi is a powerful library to get your REST API documented.

Check out other Open API-related tutorials to learn more about how to document your REST API endpoints.