Spring Boot Restful API Manuscript, OpenAPI Specification, and Generator

Kishan Kesari Gupta
TechVerito
Published in
8 min readNov 9, 2022

--

Documenting Restful APIs Using OpenAPI Specification

In recent years, RESTful web services have attracted much attention and practically taken over as the industry standard. It has not only surpassed its more sophisticated competitor, SOAP but has also taken over as the standard option in the design and implementation of APIs.

An API is a contract that API publishers and users must follow to communicate effectively. An API should specify its different elements, such as the endpoints it offers, the actions, the endpoints support, and the result it produces for a request, much like most other contracts do in order to function as expected. Additionally, an API changes over time to satisfy ever-changing demands. In this case, appropriately documenting an API is essential for better customer service. Also, as functioning with Agile, one of the precepts stands for “Working Software Over Comprehensive Document” from the Agile Manifesto, which shows the importance of a manuscript.

However, how do we describe our APIs? How can we specify the collection of elements that make up a well-documented API? Additionally, we continued to update our services, necessitating the maintenance of several versions of these APIs. There might be numerous endpoints in an API. How are all these endpoints and their activities ever going to be documented? Manually? never. How can we even guarantee that our API documentation is clear to our users? Is it even possible to normalize API manuscript creation procedures that will continuously monitor the changes made on API and update the API manuscript?

Yes, Using the OpenAPI Specification (formerly known as Swagger), we can create, document, and use REST APIs. Also, having the ability to let APIs specify their architecture is the foundation of all its virtues.

About OpenAPI

  • An OpenAPI is an open-source tool for creating API documentation, interacting with APIs, and developing APIs.
  • OpenAPI helps with creating and updating API documentation and is very time-efficient. Additionally, there is no need to update the manuscript each time the code is updated.
  • OpenAPI is a standard specification for how to document your API. It doesn’t automatically update the documentation. Various OpenAPI tools do that.
  • OpenAPI outlines patterns, standard behavioral norms, and a RESTful API interface. Dev teams don’t have to strain their brains trying to understand, use, and alter foreign APIs.
  • OpenAPI provides a resource. The API standardization tool embedded into Swagger Hub ensures that your code complies with the corporate design principles.

Objective of API Manuscript Using OpenAPI

From monolithic systems, we have transitioned to microservices. REST APIs are the foundation for microservices, the whole design. In contrast, these REST APIs’ documentation enhances the developer experience.

The productivity of new developers will increase since they won’t be dependent on an expert who must devote time to explaining how an API is designed and functions.

It makes maintenance and upgrades of inter-dependent microservices since they are more informed about your resources, techniques, related requests, and responses.

Removes limitations imposed on development by specification dependencies on the (front-end/back-end). Additionally, allow the early detection of errors and problems in the architectural design of the API.

Reduces the time and hassle required to comprehend how the API operates and to decode unforeseen problems that may occur when using it.

Evolution of OpenAPI (formerly Swagger)

OpenAPI has evolved as a straightforward source definition for RESTful APIs

In 2010, Swagger debuted as a straightforward open-source protocol for creating RESTful APIs specifications. The Swagger UI, Swagger Editor, and Swagger Codegen are examples of open-source tools to create OpenAPI specifications, auto-generate server/client barebone structure and view/interact with OpenAPI Specification specified in the standard. A vast ecosystem of community-driven tools was produced by the Swagger project, which included standard and open-source tools.

To explicitly standardize the way REST APIs are described, Open API Specification launched a new edition in 2017. The OpenAPI Initiative was established to provide open and transparent guidance for the OAS’s development. Since then, Swagger has grown to be the most well-liked set of tools for maximizing the OAS’s potential throughout the API lifetime.

In the Spring Boot project, Open API Specification included the springdoc-open API Java library in 2019 to provide the Restful API manuscript.

Let’s create OpenAPI Specification and analyse how to use it

Here, we’ve developed a tourism project that makes use of API to display a list of tour packages for various nations, a list of activities users may do, and locations they can visit. As a result, a user can reserve a tour package and alter it to suit their requirements.

To produce a RESTful APIs manuscript, we must make a few configurations in our spring boot application. We’ll use the 2019-introduced springdoc-openapi dependency.

The following springdoc-openapi dependency needs to be added to the pom.xml file inside the dependencies section.

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

The springdoc-openapi requirement comes in several versions. Check out the link here if you need another version: springdoc-openapi-ui

After adding this dependency, we must annotate the spring boot application main class with the OpenAPIDefinition annotation to enable the openapi specification for constructing RESTful API manuscripts.

The OpenAPIDefinition annotation to the main spring boot application class is represented by the below code.

//TourismApplication.java
package com.tourism;

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

@SpringBootApplication
@OpenAPIDefinition
public class TourismApplication {
public static void main(String[] args) {
SpringApplication.run(TourismApplication.class, args);
}
}

A manuscript of RESTful APIs for a tourism project is created after the aforementioned configurations. Additionally, after every build, if a new API is added for a certain controller, it will update the manuscript with it.

A list of APIs organized controller-wise will appear in a manuscript produced by OpenAPI. It also displays the schema list and its structures.

The OpenAPI-generated document for tourism is shown below. Subsequently, launch the Spring Boot application. Visit /swagger-ui/index.html to access a manuscript.

Developers can benefit from the above-generated manuscript because they won’t need to rely on an expert who must spend time describing how an API operates.

The developer can test, comprehend, and use API with various data. Here, we clicked on the get request for /api/countries, which would return all of the trip packages for each country including places and activities.

The execution of the get request for “/api/countries” is displayed in the below image along with the response.

Let’s see one more GET request call for a specific country tour package. Here, the country name will be sent using the path variable, and a particular country tour package will be returned.

After the list of APIs, there is a schema section that reveals the model’s structure and relationships with other models. Moreover, it displays the data type and highlights necessary fields with an asterisk sign.

The schema structures and associations with other tables are displayed in the picture below.

Thus, this OpenAPI manuscript is about a set of APIs and a schema structure. To see how a JSON or YML file is created following an OpenAPI definition shown in swagger-ui.html. We must go to the base address followed by /v3/api-docs.

Let’s navigate to the /v3/api-docs route to see the OpenAPI Specification in JSON format, as shown below.

{
"openapi": "3.0.1",
"info": {...},
"servers": [{...}],
"paths": {
"/api/countries": {
"get": {...},
"post": {...}
},
"/api/countries/{id}": {
"put": {...},
"delete": {...}
},
"/api/countries/{name}": {
"get": {...}
},
"/api/places": {
"get": {...},
"post": {...}
},
"/api/places/{id}": {
"put": {...},
"delete": {...}
},
"/api/places/{name}": {
"get": {...}
},
"/api/activities": {
"get": {...},
"post": {...}
},
"/api/activities/{id}": {
"put": {...},
"delete": {...}
}
},
"components": {
"schemas": {
"Activity": {...},
"Place": {...},
"Country": {...}
}
}
}

Therefore, we can create client code utilizing the OpenAPI specification JSON file mentioned above. Let’s look at how to use OpenAPI generators to develop client code in the below section.

Using OpenAPI generators, let’s create the client code

Here, let’s reverse-engineer the process of creating client code from the tourism specification file displayed above. With openapi-generator, we will use that tourism-specification.json file to produce client code.

OpenAPI Generator is a technique to construct API client code, server stubs, and some configurations from openapi manuscripts. The primary goal of OpenAPI Generator is user-friendliness; it markets itself as a technique for integrating and utilizing OpenAPI documents to lighten the load on new development and technologies.

Writing APIs is made easier using the OpenAPI Generator. If the user first creates a specification in yaml or json while taking into account the entire number of APIs required and their respective schema structures. Then, by reading the specification, the generator will produce the API structure and related model class.

Let’s create a new spring project with the Maven implementation to show how the openapi-generator is operated in a typical workflow. We must add the following dependency in the pom.xml file as given below and copy the tourism-specification.json file described above to the location (/src/main/resources).

Below is some dependency that needs to be added inside the dependencies section in the pom.xml file.

<!-- openapi tools dependency -->
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator</artifactId>
<version>6.2.1</version>
</dependency>
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>0.2.4</version>
</dependency>

Below are some plugins and configurations that need to be added inside the plugins section in the pom.xml file. Therefore, the tourism-specification.json file location will be a value of the inputSpec tag present in the configuration section.

<!-- openapi tools plugin-->
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>6.2.1</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>
${project.basedir}/src/main/resources/tourism_specification.json
</inputSpec>
<generatorName>spring</generatorName>
<apiPackage>com.tour.springtourism.api</apiPackage>
<modelPackage>com.tour.springtourism.model</modelPackage>
<supportingFilesToGenerate>
ApiUtil.java
</supportingFilesToGenerate>
<configOptions>
<delegatePattern>true</delegatePattern>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<proc>1.8</proc>
</configuration>
</plugin>

After adding all dependencies, plugins, and configurations in pom.xml, the next step is to open the maven console and run “mvn clean install” command. It generates the client code according to the openapi specification file(tourism-specification.json).

As soon as the command is successfully executed, you will notice that the client code is generated inside the classes folder in the target package. Hence the process of developing client code from openapi specification is done.

Conclusion

As a result, this blog uses a straightforward configuration to demonstrate the value of API documentation. With the assortment of components that make up a well-documented, it solves the issues with describing our APIs. Additionally, it keeps track of the various API versions and updates the API document as needed. It also shows a reverse-engineering process to construct API client code, server stubs, and some configurations from openapi manuscripts.

Want to get in touch?

Please reach out to me on LinkedIn.

--

--