DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. Rapid Application Development With API First Approach Using Open-API Generator

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.

Milan Sonkar user avatar by
Milan Sonkar
·
Jan. 30, 19 · Tutorial
Like (8)
Save
Tweet
Share
22.81K Views

Join the DZone community and get the full member experience.

Join For Free

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 openApiGenerate. This 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.

API application Rapid application development unit test Spring Framework

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Choose the Right Streaming Database
  • Full Lifecycle API Management Is Dead
  • gRPC on the Client Side
  • Reliability Is Slowing You Down

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: