Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rapid Application Development With API First Approach Using Open-API Generator

DZone's Guide to

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.

· Microservices Zone ·
Free Resource

Record growth in microservices is disrupting the operational landscape. Read the Global Microservices Trends report to learn more.

Microservices 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

  1. Add the Kaizen OpenApi Editor Eclipse plugin using the Eclipse marketplace. This will help us to automatically generate the OpenApi YAML configuration file.

  2. Create a Gradle project.

  3. 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.

  4. 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

  1. Open a Terminal in Eclipse or your machine and navigate to your project home directory. Run following command: gradle openApiGenerateThis command will generate four packages.

    1. Invoker package: In the code, it is com.milan.openapi.employee, and contains the SpringApplication (OpenAPI2SpringBoot) class with the main method. 

    2. 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() and updateEmployee() of the EmployeesAPI interface have been overridden manually in the EmployeesAPIController class to give meaningful response.

    3. Model package: Contains the classes for the model. In the code, it is com.milan.openapi.employee.model with Employee and Error as two model classes.

    4. Configuration package: Containing classes related to Swagger UI. This is org.openapitools.configuration.

  2. You can add business logic and exception handling code to the generated application by adding Service and ExceptionHandlerclasses. 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 the EmployeeService class has been added manually so it returns a meaningful response. The methods in the EmployeesApiController class have been customized manually as well.

  3. Run your project as a Spring Boot application via Eclipse or the command prompt.

  4. Access the generated APIs using Postman or any other REST client.

  5. 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.

Learn why microservices are breaking traditional APM tools that were built for monoliths.

Topics:
microservice design ,microservice ,api development ,microservices tutorial ,restful apis

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}