Introduction

This tutorial will show you an example on how to document REST APIs using OpenAPI 3. When creating a REST API, good documentation is instrumental. Here we will use OpenAPI 3 in Spring application for creating documentation for REST APIs. We create and deploy REST services but we do not have an option to let others know in a single place, where REST services, having methods, request body, request params, etc., are exposed for consumption. Here we will take a look at SpringDoc — a tool that simplifies the generation and maintenance of API docs, based on the OpenAPI 3 specification for Spring application.

Besides generating the OpenAPI 3 specification itself, we can integrate springdoc-openapi with Swagger UI so that we can interact with our API specification and exercise the endpoints. The Swagger specification is a powerful definition format to describe RESTful APIs. The Swagger specification creates a RESTful interface for easily developing and consuming an API by effectively mapping all the resources and operations associated with it. It’s easy-to-learn, language agnostic, and both human and machine readable.

Related Posts:

Prerequisites

Eclipse 2019-12, Java at least 1.8, Spring Boot 2.2.4, SpringDoc Open API 1.1.49, Gradle 6.1.1, Maven 3.6.3

Create Project

Create a gradle or maven based project in Eclipse. The name of the project is spring-openapi-documentation.

If you are creating gradle based project then you can use the below build.gradle script to build your project.

buildscript {
	ext {
		springBootVersion = '2.2.4.RELEASE'
	}
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

plugins {
    id 'java-library'
    id 'org.springframework.boot' version '2.2.4.RELEASE'
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
    implementation('org.springdoc:springdoc-openapi-core:1.1.49')
}

If you are creating maven based project then you can use the below pom.xml file to build your project.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>spring-openapi-documentation</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.4.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springdoc</groupId>
			<artifactId>springdoc-openapi-core</artifactId>
			<version>1.1.49</version>
		</dependency>
	</dependencies>

    <build>
        <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>at least 8</source>
					<target>at least 8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

REST APIs

Now we will expose two REST APIs using Spring boot framework, one is with http method GET for just returning Hello World! and another is to greet a person for a given name of the person with http method POST.

package com.roytuts.spring.openapi.documentation.rest.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestApi {

	@GetMapping("/")
	public ResponseEntity<String> greet() {
		return new ResponseEntity<String>("Hello World!", HttpStatus.OK);
	}

	@PostMapping("/greet")
	public ResponseEntity<String> greet(@RequestBody String name) {
		return new ResponseEntity<String>("Hello, " + name, HttpStatus.OK);
	}

}

Main Class

A class is having main method with @SpringBootApplication is enough to deploy the Spring Boot application on the embedded Tomcat server.

package com.roytuts.spring.openapi.documentation;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringOpenApiDocumentationApp {

	public static void main(String[] args) {
		SpringApplication.run(SpringOpenApiDocumentationApp.class, args);
	}

}

Testing the Application

Once your application is deployed successfully on Tomcat server you can access the documentation URL http://localhost:8080/v3/api-docs in the browser. The default path of the OpenAPI documentation is /v3/api-docs.

The output of you should get is given below:

{"openapi":"3.0.1","info":{"title":"OpenAPI definition","version":"v0"},"servers":[{"url":"http://localhost:8080","description":"Generated server url"}],"paths":{"/":{"get":{"operationId":"greet","responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"type":"string"}}}}}}},"/greet":{"post":{"operationId":"greet_1","requestBody":{"content":{"*/*":{"schema":{"type":"string"}}}},"responses":{"200":{"description":"default response","content":{"*/*":{"schema":{"type":"string"}}}}}}}},"components":{}}

You can customize the path in application.properties file, for example, springdoc.api-docs.path=/api-docs. Therefore the documentation path is /api-docs and you can now access at http://localhost:8080/api-docs and you will see the same output as above.

The OpenAPI definitions are in JSON format by default. For yaml format, we can obtain the definitions at http://localhost:8080/v3/api-docs.yaml or http://localhost:8080/api-docs.yaml (if you have changed the path in application.properties file). The content you will get is:

openapi: 3.0.1
info:
  title: OpenAPI definition
  version: v0
servers:
- url: http://localhost:8080
  description: Generated server url
paths:
  /:
    get:
      operationId: greet
      responses:
        200:
          description: default response
          content:
            '*/*':
              schema:
                type: string
  /greet:
    post:
      operationId: greet_1
      requestBody:
        content:
          '*/*':
            schema:
              type: string
      responses:
        200:
          description: default response
          content:
            '*/*':
              schema:
                type: string
components: {}

Now you see the documentation is readable but not pretty good to be read. Therefore we will use Swagger UI along with OpenAPI 3 specification as we said earlier at the beginning of the tutorial.

So remove the dependency springdoc-openapi-core from build.gradle or pom.xml file and include the following dependency into build.gradle or pom.xml file accordingly.

implementation('org.springdoc:springdoc-openapi-ui:1.2.32')
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.2.32</version>
</dependency>

Next task is to rebuild your application and deploy the application by executing the main class.

Now access the Swagger UI at URl http://localhost:8080/swagger-ui.html, if you want to customize the path then you can do it in the application.properties file springdoc.swagger-ui.path=/swagger.html, now your URL will be http://localhost:8080/swagger.html.

Now you will see the similar screen on the browser as shown in the below image:

document rest apis using openapi 3

You can click GET or POST to expand it and click on Try it out. Next click on Execute button once it appears.

For GET request you will see output as Hello World!

For POST request you have to set Request body after clicking on Try it out button. For example, I set Soumitra to the Request body. Therefore I get the output as Hello, Soumitra once I click on Execute button.

Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *