Spring Boot: Generating server and client code using OpenAPI 3 specs (2023)

REST APIs are ubiquitous in today's world, from payments to communications and banking. Developers can plug in virtually any specialized service they need for their applications.

So it's not surprising that at PALO IT we often develop APIs for our customers and integrate external APIs into our backend applications. Our own and external APIs can get very large and complex, making them time consuming to write by hand. Fortunately, there are some nifty techniques that make our lives easier as developers and avoid writing repetitive code.

Enter OpenApi 3 specs and code generation!

Imagine someone needs access to our newly developed API. In the past, we shared our endpoint definitions in a non-standard way, like Excel spreadsheets. Consumers of our API would need to implement a client in their application. For large APIs, this can take a long time. In order not to have to reinvent the wheel, the open API specification was created. It allows us to define our REST API contract in a standardized format and easily share it with others.

Therefore, an ecosystem of editors and code generation tools has been built around the open API specification (current version 3.1 at the time of writing). These tools allow us to create API documentation and generate clients and servers for various programming languages ​​and frameworks. This article focuses on using code generation with the popular Javaspring boot framewhich is used in more than a few of our projects.

The definition

Before we get into the code, we need to establish some definitions...

Open API specification

IT ISOpen API specification(OAS) defines a standard, language-independent interface to RESTful APIs that allows humans and computers to discover and understand service capabilities without access to source code, documentation, or examining network traffic. When defined correctly, a consumer can understand and interact with the remote service with a minimum of implementation logic.

customer number

Client code is any client SDK that we can use to call a remote REST API. In the context of Spring Boot, client code is typically written using HTTP clients like thisbreak modelor the most recently introducedweb client.

server code

Server code refers to any code needed to build a REST API server. With Spring Boot, this is typically done using the servlet API basespring netor newer, no blockingspring web flow.

GENERATION-Code

The code generation that we will learn in this tutorial is done with theOpen the API Builder. It is a community project, widely used by many well-known companies, capable of generating client code or server stubs from an open API specification in aVariety of programming languages ​​and frameworks. There are many ways to use the generator. It is available as a Maven plugin, npm module and standalone JAR. In the following sections, we'll use the Maven plugin for simplicity, as the Spring Boot project uses it as a build management tool.

As a side note, the OpenAPI generator has been forked fromSwagger-Codeto simplify the original and allow for greater community ownership.

(Video) Spring Boot | Documenting Microservice Using OpenAPI 3.0 specification | javatechie

learning area

With this tutorial, we will show you how to generate server-side and client-side code from an Openapi 3 specification. The v3 specification is the latest iteration of Openapi and adds many new ones to the previous v2 version.features and improvements.

For the sake of simplicity, theSwagger Zoohandlungis used for generation. It's a simple REST API example that demonstrates the features of the Open API specification, including authorization, HTTP schemes, and API descriptions.

server

For the server side, the generator generates traditional Spring Web based code.

Client

To demonstrate client code generation, we'll use the reactive WebClient. At PALO IT, we prefer the web client for our projects because it simplifies simultaneous calls compared to the Rest Template. Additionally, RestTemplate is no longer under active development and will remain inmaintenance mode. Therefore, WebClient should be preferred for new projects.

previous requirements

Before we start, we need to make sure we have all the tools we need to run the app. Tools and installation instructions are below.

project structure

To familiarize yourself with the components and structure of the project, areas of interest are described below.

The Petstore Openapi specification in YAML format is maintained insrc/main/resources/openapiBookbinder. Both the server and the client contain the same specs, but they have been kept in separate folders for convenience.

  1. The generated WebClient code
  2. Common configuration for WebClient, SpringDoc API documentation, and Jackson parser
  3. The generated Spring web server stubs
  4. Customization of build templates. Sometimes custom configurations are required for the build process when the default templates are not enough. More about this at custom generator templates
  5. Tests for the generated server and client.

The OpenAPI generator configuration can be found in the pom. To separate the client and server builder configuration, Maven profiles were used as shown below.

Spring Web Server Builder-Konfiguration

Configure the WebClient Generator

starting

Clone the Git repository.

(Video) OpenAPI Generator Demo for Spring Boot | Generate Web & WebFlux Server Code | Swagger UI

Import the Maven project into the spring-boot-openapi-codegen with your favorite IDE.

generate customers

Using a terminal, navigate to the project and run the following command to generate the client code.

The generated code can be found atMetaDirectory.

  1. Contains the generated APIs
  2. Shared classes related to authorization
  3. generated models
  4. Reusable Shared Support Classes

After compilation is complete, the template and API packages (1st and 3rd) are copiedcom.paloit.clientpetstore.webclient.The support and authorization classes are also copied and included in thebeginnerjauthenticationPACKAGES

Client startup and usage

The client must be defined as a jumping bean. it happens insidecom.paloit.config.ApiClientConfigClass. A simple example is shown below and should be self-explanatory.

According to the definition ofPetApiLike Spring Bean, it can be autowired and used to call the external API as shown below.

Custom builder templates

The OpenAPI generator usedmustache stencilsto generate client implementations or server stubs. In most cases these are enough to use right away. For custom use cases, these can be customized to generate the desired code.

(Video) Generate Client code from OpenApi / Swagger in Camunda

Templates for all programming languages ​​supported by the generator can be found on itsGit-RepositoryName.

Templates can be replaced using Maven's OpenAPI generator configurationplantillaDirectorioLabel. If a template with the same filename as the original is found in the specified directory, it will replace the default template.

The overridden templates for the WebClient have been copied to the local/src/main/resources/generator-template-overrides/webclientdirectory ofopenapi-generator/src/main/resources/Java/libraries/webclientFolders in the OpenAPI Generator Git repository.

This example uses the generator templates to change a modifier with the generated client to access the ResponseSpec and allow us detailed handling of HTTP errors. By default, the PetApi client methodAddpetsreturns only one monkey as seen below and theaddPetRequestCreationThe method is private.

IT ISmoustachethe model is changed on line 72 so that theaddPetRequestCreationThe method becomes public and accessible. The corresponding change is shown in bold below.

generate servers

The server is similarly generated and illustrates thisFirst approach to API development. First, the open API specification is created and a server stub is generated from it. The development team then adds implementations for the API.

In order to be able to rebuild the server at any time without affecting deployments, the delegated pattern is used and explained later.

Navigate to the root of the project using a terminal and run the following command to generate the server code.

(Video) Spring Boot Open Api example | generating API Code from Specification | Spring Boot 2 | OpenApi 3

The generated code can be found in the destination folder.

After compilation is complete, the model and API packages are copied to theserver.petstorePackage. The implementations are inRules package and must implement the delegated interfaces. Delegated interfaces define default implementations for all APIs and return HTTP 501 (Not Implemented) if not overridden.

IT ISPetApiControlleruse default valuePetApiDelegateif we don't define ours. However, if we define ours with custom implementations as shown below, it will be used automatically.

Note that our delegated implementation must be a Spring Bean and the@ComponentsThe annotation is added at the beginning of the class.

The delegate pattern effectively separates the API definition from its implementation, and both can be modified independently. The default delegate, API and templates can be regenerated without affecting the implementation and vice versa.

run app

Use the following command to launch the application. A Swagger UI web interface can be accessed athttp://localhost:8090/openapito examine and interact with the REST API.

perform tests

Conclusion

In this article, we show you how you can speed up development with Spring Boot by generating server and client code. Using these techniques helped our team of experts at PALO IT quickly develop our own REST APIs and integrate external APIs into our applications. By openly sharing our approachdevelopment, we hope it will benefit you, our dear readers, and spark interest in our other practices. ftw open source!

Get in touch

LAMAis always looking for passionate developers to join our team. Are you interested in learning, coding and applying cutting-edge technologies to empower our customers and make the world a better place? Don't think about it anymore and applyon here!

(Video) Generating API Client Libraries from OpenAPI Spec - Jordan Adler

Interested in developing your own REST APIs? Join our team of experts and let's build something amazing together.

Spring Boot: Generating server and client code using OpenAPI 3 specs (1)

FAQs

How to generate OpenAPI spec from Spring Boot? ›

To summarize, you just add the maven dependency for springdoc-openapi into your application and when you bootRun, go to path http://server:port/v3/api-docs.yaml/ and you will download an Open API 3.0 spec file in yaml, generated from your application's code.

What is the difference between client and server in OpenAPI generator? ›

The client is a library you could use in the application that consumes the API, in that you can use it as is make requests to the API described by the OpenAPI definition. The server is simply an example server application that provides the HTTP interface described in the OpenAPI.

Which is used in generating server stubs and libraries from OpenAPI spec? ›

Swagger Codegen – generates server stubs and client libraries from an OpenAPI definition. Swagger Editor Next (beta) – browser-based editor where you can write and review OpenAPI and AsyncAPI definitions.

How to generate OpenAPI spec from Java code? ›

Two Ways to Create OpenAPI Specs
  1. Manually Create an OpenAPI Spec. One option is to have someone sit down, take a look at their API and manually transform it into an OpenAPI definition. ...
  2. Create an OpenAPI Spec From Code. ...
  3. PHP. ...
  4. Java. ...
  5. Javascript/Node. ...
  6. Python. ...
  7. Ruby. ...
  8. Go.
Feb 9, 2021

How to write OpenAPI Specification? ›

Building a specification requires some simple setup. You must define a title, description, and version number for your API. You also must indicate which Swagger version you're using in the type field: This will be your starting point (otherwise customized to your project) when crafting your API definitions.

How do I create an OpenAPI Swagger spec? ›

If you're designing your API and don't yet have the API built, check out our Getting Started with SwaggerHub guide.
  1. Go to Swagger Inspector. ...
  2. Make calls to your API. ...
  3. Select requests in the History and create API definition. ...
  4. Follow the prompts to go to SwaggerHub.
  5. Name your API. ...
  6. Your definition is there!

How to use OpenAPI Swagger in Spring Boot? ›

Documenting a Spring REST API Using OpenAPI 3.0
  1. Overview. ...
  2. Setting up springdoc-openapi. ...
  3. Integration with Swagger UI. ...
  4. Integrating springdoc-openapi With Spring WebFlux. ...
  5. Exposing Pagination Information. ...
  6. Using springdoc-openapi Maven Plugin. ...
  7. Automatic Document Generation Using JSR-303 Bean Validation.
Jan 30, 2023

How do I get OpenAPI Specification from Swagger UI? ›

How to generate OpenAPI from existing APIs. Head over to Swagger Inspector, and insert the end point of the resource you want to have documented. You can then navigate to the right panel from the History section of Swagger Inspector, and click "Create API definition" to create the OAS definition.

How do I convert Postman collection to OpenAPI? ›

API Transformer: How to convert your Postman Collection to OpenAPI format.
  1. Click on the "Upload Postman Collections" Button.
  2. Upload your Postman Collection file and convert.
  3. Download your OpenAPI converted file.

Videos

1. Spring Boot + Swagger 3 (OpenAPI 3) Hello World Example
(JavaInUse)
2. Introducing OpenAPI Generator
(Cloud-Native Development)
3. How to set up openapi on springboot in less than 5 minutes
(lemoncode21)
4. #28.How to implement Open API 3.0 ( Swagger 3) in SpringBoot Application ? @JavaExpress
(Java Express)
5. Api-First driven development - Using swagger code gen, OpenApi & Spring Boot
(Mike Teaches Programming)
6. OpenAPI Specification ( Swagger ) Crash Course in Spring Boot
(One O One Code)
Top Articles
Latest Posts
Article information

Author: Dr. Pierre Goyette

Last Updated: 11/19/2022

Views: 6200

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Dr. Pierre Goyette

Birthday: 1998-01-29

Address: Apt. 611 3357 Yong Plain, West Audra, IL 70053

Phone: +5819954278378

Job: Construction Director

Hobby: Embroidery, Creative writing, Shopping, Driving, Stand-up comedy, Coffee roasting, Scrapbooking

Introduction: My name is Dr. Pierre Goyette, I am a enchanting, powerful, jolly, rich, graceful, colorful, zany person who loves writing and wants to share my knowledge and understanding with you.