Generating JAX-RS APIs from Swagger definitions

Under: web-dev Tags: #Java #OpenAPI #API

The sample project is available on GitHub.

With the virtues of OpenAPI specifications, it’s a waste of human resources to create API services by hand. Despite that thought what shocked me the most was the lack of documentation from Swagger end on their code-generation plugin. As the generation tool is fully featured and constantly updated but documentation is sparse regarding the availability of JAX-RS as an option.

Photo by Harry Cunningham on Unsplash Photo by Harry Cunningham on Unsplash

This guide will explore how the swagger-codegen-maven-plugin can be used to generate API interfaces in Java with Maven.

Maven Configuration

The plugin is configurable as maven goal, where you are able to define the generation source folder and also packages for the generated artifacts.

I’ve opted to use generic Response as It’s much more intuitive and clean to do so instead of the default model return type which is specified in this section

The generation process can be invoked with ‘mvn clean instal’

and if you don’t fancy the generation process being re-triggered on each run after the initial invocation true can be set in place.

API Implementation

The maven specified invokerPackage will contain the generated API template ready to be implemented. Now we can go ahead and implement the given templates.

Afterward, we need to add the service bean to beans.xml and voila we’re done.

What’s remaining is to compile the project and test it out, I added Docker compose to quickly start up an instance of tomcat to do so.