Rapid Application Development With API First Approach Using Open-API Generator
A tutorial on developing an API microservices and deploying using Swagger UI on the front-end and Spring Boot on the backend.
Join the DZone community and get the full member experience.
Join For FreeMicroservices are the new way of building loosely coupled, highly scalable and distributed applications. There are multiple ways of developing microservices like REST, GRPC, Thrift, and many more. However, REST is the most popular choice because of the maturity of the model, availability of tools and developer pool. In this article, I am going to explain how to accelerate your API development by using OpenAPI Generator. OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3). If used consistently, we can save a lot of development effort for creating APIs conforming to OpenAPI Spec. Here I am using OpenAPI Gradle plugin and Kaizen OpenApi editor for Eclipse to generate server-side (available here ) and client-side code (available here) for a SpringBoot-based application.
Project Set Up
Add the Kaizen OpenApi Editor Eclipse plugin using the Eclipse marketplace. This will help us to automatically generate the OpenApi YAML configuration file.
Create a Gradle project.
Create a file, openapi-employee-service.yaml (any file name), using teh Kaizen OpenApi editor under /src/main/resources. This will create a sample Petstore YAML schema based on the OpenApi spec in the new file.
Modify the openapi-employee-service.yaml file to your requirements. This is the base definition file which will be used to automatically generate the server and client codebase.
Gradle Dependencies
Add the following dependency to put the openapi-generator-gradle-plugin on your classpath
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:3.3.4"
}
Add the following plugin to use open-api-generator in your build.gradle file.
apply plugin: 'org.openapi.generator'
Add the below task for automatic code generation. This will generate a server stub for SpringBoot/SpringMVC-based RESTful APIs. This will also generate a fully working Swagger UI for the generated code. The Swagger UI is accessible at http://localhost:8081/swagger-ui.html#/ if you specify the base-URL port as 8081 in openapi-employee-service.yaml under servers: http://localhost:8081.
openApiGenerate{
generatorName = "spring"
inputSpec = "$rootDir/src/main/resources/openapi-employee-service.yaml".toString()
outputDir = "$rootDir".toString()
apiPackage = "com.milan.openapi.employee.api"
invokerPackage = "com.milan.openapi.employee"
modelPackage = "com.milan.openapi.employee.model"
modelFilesConstrainedTo = []
configOptions = [
dateLibrary: "java8"
]
}
The openApiGenerator supports other options for generating server code as well, like Ada, C# (ASP.NET Core, NancyFx), C++ (Pistache, Restbed), Erlang, Go (net/http, Gin), Haskell (Servant), Java (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy, Play Framework, PKMST), Kotlin (Spring Boot), PHP (Laravel, Lumen, Slim, Silex, Symfony, Zend Expressive), Python (Flask), NodeJS, Ruby (Sinatra, Rails5), Rust (rust-server), Scala (Finch, Lagom, Scalatra). More details can be found at the GitHub repo; you can also see all the supported server stub options by running the below command:
gradle openApiGenerators
Steps to Generate Server Code
Open a Terminal in Eclipse or your machine and navigate to your project home directory. Run following command:
gradle openApiGenerate
. This command will generate four packages.Invoker package: In the code, it is com.milan.openapi.employee, and contains the SpringApplication (OpenAPI2SpringBoot) class with the main method.
API package: In the code. it is com.milan.openapi.employee.api which contains classes related to API and request handling along with there default implementation. The default implementation can be overridden as per your needs. The methods
createEmployee()
,deleteEmployeetById()
,listEmployees()
,showEmployeetById()
andupdateEmployee()
of the EmployeesAPI interface have been overridden manually in theEmployeesAPIController
class to give meaningful response.Model package: Contains the classes for the model. In the code, it is com.milan.openapi.employee.model with
Employee
andError
as two model classes.Configuration package: Containing classes related to Swagger UI. This is org.openapitools.configuration.
You can add business logic and exception handling code to the generated application by adding
Service
andExceptionHandler
classes. This is the only code developers have to write while creating a Spring Boot or any RESTful based application. The package com.milan.openapi.employee.service along with theEmployeeService
class has been added manually so it returns a meaningful response. The methods in theEmployeesApiController
class have been customized manually as well.Run your project as a Spring Boot application via Eclipse or the command prompt.
Access the generated APIs using Postman or any other REST client.
Access Swagger UI using url http://localhost:8081/swagger-ui.html#/. You can invoke your RESTful endpoints via Swagger UI as well.
Client and Unit Test Generation
Create another Gradle project (openapi-employee-client) for your client and follow steps 1-4 outlined above in the Project set up section.
Follow steps 1 and 2 above for adding Gradle dependencies.
Add the below task for automatic client code generation. This will automatically generate the client code for your generated server along with unit test cases.
openApiGenerate{
generatorName = "java"
inputSpec = "$rootDir/src/main/resources/openapi-employee-service.yaml".toString()
outputDir = "$rootDir".toString()
apiPackage = "com.milan.openapi.employee.api"
invokerPackage = "com.milan.openapi.employee"
modelPackage = "com.milan.openapi.employee.model"
modelFilesConstrainedTo = []
configOptions = [
dateLibrary: "java8"
]
}
For the sample client project, the EmployeeApiTest
class is created with the 5 test cases. I have just added test data and simple assert statements to run these cases against the server application.
Execute the unit test cases and verify results.
Conclusion
OpenApiGenerator is a great tool for the automatic generation of high quality RESTful API code conforming to Open API 2.0 or 3.x specification. This also generates the Swagger documentation and UI automatically. If used consistently across development teams, this can help to save a lot of development effort without any side effects.
Opinions expressed by DZone contributors are their own.
Comments