Creating OpenAPI 3.0 Documentation (with Swagger UI) in Spring Boot
Steps to Create OpenAPI 3.0 API Documentation with Swagger in Spring Boot
Firstly, you need to add “springdoc” dependency to your pom.xml file (My spring boot version is 2.6.3 and spring-doc-openapi.version is 1.6.5):
I declared a context path in application.properties (please beware that api doc url will be affected by this):
Urls for OpenAPI JSON documentation and Swagger will be:
OpenAPI Documentation JSON URL => http://localhost:8000/api/v3/api-docs)
Swagger URL => http://localhost:8000/api/swagger-ui/index.html
Later, we will create a configuration class for OpenAPI in the project:
With @Operation, you can define the purpose of your API.
@Tag helps you to label to group (such as API methods in a REST Controller, etc.). Please pay attention to both @Tags and “tags” field in @Operation.
You can use @Parameter annotation with “ParameterIn.HEADER” to declare a header parameter.
With @ApiResponses, you can declare each of your status codes (with @ApiResponse) that your api may return, with their explanations.
@Content with @Schema you can declare your response type. You can specify it with “type” or “implementation”.
If the response is a list of objects, you can specify it with @ArraySchema as:
content = @Content(array = @ArraySchema(schema = @Schema(implementation = OrderInfo.class)))
Below, I share “books” REST Controller implementation which includes GET, POST, PATCH api’s:
Here are some fragments from OpenAPI documentation served via “http://localhost:8000/api/v3/api-docs” (viewed with JSON Viewer Chrome Extension which you can install from here.)
And, here are fragments from Swagger documentation (http://localhost:8000/api/swagger-ui/index.html) :
References and Other Useful Links: