How To Add OpenAPI And Swagger In Spring Boot 3

Lemoncode21
2 min readDec 25, 2022

--

In This articile we want to add openAPI to springboot 3. When building REST APIs, it is essential to have documentation so that it is easier to find out what are the APIs that have been built.

There are several topics that I will discuss, namely:

  1. How To Add OpenAPI 3.0 And Swagger To Spring Boot 3
  2. Create Custom Response
  3. Create Custom Request
  4. Grouping endpoint
  5. Add Security Authentication

Of course, the 4 topics above represent how to use openAPI on RestAPI as documentation.

1. How To Add OpenAPI 3.0 And Swagger To Spring Boot 3

Step-1: Let’s start by adding OpenAPI 3.0 maven dependency to our pom.xml

Step-2: Add new class Springdoc to enable openapi documentation by adding @OpenAPIDefinition.

With steps 1 and 2 we configured OpenAPI 3.0 default documentation for Rest API’s

2. Create Custom Response

To create a custom response, it’s very easy, you just need to add @Operation above your controller function.

3. Create Custom Request

To make your custom request, simply add @RequestBody from the @io.swagger.v3.oas.annotations.parameters.RequestBody library inside the function parameter.

4. Grouping endpoint

If you need a grouping feature in openAPI to group endpoints based on business needs, you can use the GroupedOpenApi function. The way you do this is to add a new @bean to the spring doc class as below.

5. Add Security Authentication

You can also add authentication security in open API. The method is quite easy, just add @SecurityScheme to your open API configuration file. For more details, you can see the code below.

On the schema attribute you can change it with basic. if you replace it with basic then the login security is the username and password. Because I use JWT bearer so I use scheme bearer. then you add a security attribute in each of your APIs, for example like below.

Summary

In this article, we added OpenAPI 3.0 configuration to existing Sprint Boot Rest API’s by add OpenAPI dependency in pom.xml. You can find the complete source code for this tutorial on Github and Video.

--

--

Lemoncode21
Lemoncode21

No responses yet