Creating OpenAPI 3.0 Documentation (with Swagger UI) in Spring Boot

Nil Seri
3 min readApr 25, 2022

Steps to Create OpenAPI 3.0 API Documentation with Swagger in Spring Boot

Photo by Kelly Sikkema on Unsplash

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):

<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${spring-doc-openapi.version}</version>
</dependency>

I declared a context path in application.properties (please beware that api doc url will be affected by this):

server.servlet.context-path=/api
server.port=8000

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:

Annotations

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.)

OpenAPI Doc — General Info and Tags
OpenAPI Doc — Paths
OpenAPI Doc — Class Definitions Used in Request/Response

And, here are fragments from Swagger documentation (http://localhost:8000/api/swagger-ui/index.html) :

Swagger — General Info and Tags
Swagger — Paths
Swagger — Class Definitions Used in Request/Response

Happy Coding!

--

--

Nil Seri

I would love to change the world, but they won’t give me the source code | coding 👩🏻‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨