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. Before we get into the code, we need to establish some definitions... 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. 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 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. 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.The definition
Open API specification
customer number
server code
GENERATION-Code
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/openapi
Bookbinder. Both the server and the client contain the same specs, but they have been kept in separate folders for convenience.
- The generated WebClient code
- Common configuration for WebClient, SpringDoc API documentation, and Jackson parser
- The generated Spring web server stubs
- 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
- 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.
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 atMeta
Directory.
- Contains the generated APIs
- Shared classes related to authorization
- generated models
- 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 thebeginner
jauthentication
PACKAGES
Client startup and usage
The client must be defined as a jumping bean. it happens insidecom.paloit.config.ApiClientConfig
Class. A simple example is shown below and should be self-explanatory.
According to the definition ofPetApi
Like 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.
Templates for all programming languages supported by the generator can be found on itsGit-RepositoryName.
Templates can be replaced using Maven's OpenAPI generator configurationplantillaDirectorio
Label. 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/webclient
directory 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 methodAddpets
returns only one monkey as seen below and theaddPetRequestCreation
The method is private.
IT ISmoustache
the model is changed on line 72 so that theaddPetRequestCreation
The 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.
The generated code can be found in the destination folder.
After compilation is complete, the model and API packages are copied to theserver.petstore
Package. 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 ISPetApiController
use default valuePetApiDelegate
if 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@Components
The 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!
Interested in developing your own REST APIs? Join our team of experts and let's build something amazing together.
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? ›- 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. ...
- Create an OpenAPI Spec From Code. ...
- PHP. ...
- Java. ...
- Javascript/Node. ...
- Python. ...
- Ruby. ...
- Go.
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? ›- Go to Swagger Inspector. ...
- Make calls to your API. ...
- Select requests in the History and create API definition. ...
- Follow the prompts to go to SwaggerHub.
- Name your API. ...
- Your definition is there!
- Overview. ...
- Setting up springdoc-openapi. ...
- Integration with Swagger UI. ...
- Integrating springdoc-openapi With Spring WebFlux. ...
- Exposing Pagination Information. ...
- Using springdoc-openapi Maven Plugin. ...
- Automatic Document Generation Using JSR-303 Bean Validation.
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? ›- Click on the "Upload Postman Collections" Button.
- Upload your Postman Collection file and convert.
- Download your OpenAPI converted file.