Documenting Spring Boot REST API with OpenAPI 3.0

Shashir
Shashir
Feb 20 · 3 min read

In this article, we’ll see how to document Spring Boot application (using Kotlin) implemented in my last article.

Gadget gallery App: Kotlin + Sprint Boot +H2 database

OpenAPI 3.0 is an open-source format for describing and documenting API’s formerly known as Swagger specification.

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

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

Step-2: Enable openapi documentation by adding @OpenAPIDefinition on the main class as below.

package com.shasr.gadgetgallery

import io.swagger.v3.oas.annotations.OpenAPIDefinition
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@OpenAPIDefinition
@SpringBootApplication
class GadgetgalleryApplication

fun main(args: Array<String>) {
runApplication<GadgetgalleryApplication>(*args)
}

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

http://localhost:<app-port>/swagger-ui.html

Step-3: Lets override default URI and the order of HTTP methods displayed on Open API console (application.yml)

springdoc:
swagger-ui:
path: /gadget-gallery
operationsSorter: method

Lets try with http://localhost:8080/gadget-gallery, it will be redirected to http://localhost:8080/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config

Note: HTTP methods are displayed in alphabetical order

Default URI display error page as below: http://localhost:8080/swagger-ui.html

Step-4: Let’s start testing API’s from OpenAPI console

To Fetch all the gadgets

Github:

Summary:

In this article, we added OpenAPI 3.0 configuration to existing Sprint Boot Rest API’s by add OpenAPI dependency in pom.xml and annotating main class with @OpenAPIDefinition. We updated custom URI and ordered HTTP methods on OpenAPI console

Nerd For Tech

From Confusion to Clarification

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Shashir

Written by

Shashir

Middleware Engineer, Java/Kotlin/Spring/Kafka

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.