springdoc-openapi library allows us to automatically generate an OpenAPI specification for our rest API built with Spring Boot. This specification is also useful when we need a Swagger documentation or we want to automate client code generation.
You can find an example project with springdoc-openapi in the spring-boot-angular-scaffolding repository.
Add Maven dependencies
As a result, we now have an automatically generated OpenAPI specification for our Spring Boot project and all its REST endpoints. Just start the app and visit http://localhost:8080/v3/api-docs:
Documentation via Swagger UI
All you need to do is visit the http://localhost:8080/swagger-ui.html url and verify the generated documentation:
As we can see, the generated specification and documentation contain only basic information and use the default naming convention. We’re going to customize it with some additional configuration.
Add custom configuration
The code used below is available in the spring-boot-angular-scaffolding repository.
Customize specification with annotations
If we want to avoid implementation details leaking through names like
home-page-controller, we can customize those names with annotations. We’re going to use @Schema on our
Next, we’re going to change the controller name and add a description for our example endpoint:
As a result, we will see a more friendly version of our docs when running the app again:
Add project info
Furthermore, we can add some project details to the generated specification. Fortunately, we have project name, description and version already defined in our
Thanks to the Automatic Property Expansion feature we can use the existing build configuration. Let’s create custom properties in our
application.properties file and assign their values:
Following the Spring Boot documentation on Externalized Configuration, specifically Type-safe Configuration Properties, we’re going to create the
Finally, we can use those properties in our OpenAPI configuration class. Additionally, we can specify the license of the project as well:
Consequently, the swagger-ui page will include the specified project details:
Obviously, we will see all those changes in the specification as well:
It’s important to realize that in this example we added only one
springdoc-openapi module to our project – Spring Data Rest. However, Springdoc comes with multiple modules, offering support for Spring Security, Hateoas, Kotlin etc.
Learn more on documenting Spring Boot API
- Springdoc-openapi docs
- Springdoc-openapi Demos
- Migrating from SpringFox
- How to set up Spring Boot app documentation with Springfox