How to generate Java – Spring Code from OpenAPI YAML spec

Hi Folks,

Lets see quickly how can generate the Spring Boot code from OpenAPI Specification i.e. YAML file.

Swagger is popular tool to design the API. I’m working on some integration project and my Business Analyst shared a OpenAPI spec which describe the name of API, input parameters , data types, the output response, http error code handling and so on.

The swagger code generator is powerful utility to help developers to generate the code from YAML API specification file. Normally this approach referred as Top-Down approach where we first define the API defination and then write the code.

The Swagger-Codegen can be download from Git. Here I’m having OpenAPI version 3.0 and so clone the project from Branch 3.0.0. It can be downloaded from here.

One you clone or downloaded the zip file. Unzip it and navigate to the downloaded or cloned directory path. Like in my case I downloaded swagger-codegen-3.0.13.zip and saved it in c:/soft_downlaods.

Next step to compile and build the package, For this maven is required, if not just download the maven and set the M2_HOME environment variable.

Also make sure that you have JAVA_HOME variable set to JDK installation path. This required while compiling the code.

So I navigated to c:/soft_downlaods/swagger-codegen-3.0.13 and executed the following command

mvn clean package -DskipTests=true

It will take 3-4 minutes and will generate a jar file at modules/swagger-codegen-cli/target/swagger-codegen-cli.jar

Use this .jar file to generate the Spring code artifacts using below command

C:\soft_downloads\swagger-codegen-3.0.13> java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -i wheather_api_v.0.2.int.yaml –api-package com.ayp.weatherservice.api –model-package com.ayp.weatherservice.api.model –group-id com.ayp.weatherservice –artifact-id ayp-weatherservice-api –artifact-version 0.0.1-SNAPSHOT -l spring -o c:\my_api\aypw-service-api

Where

  • -i : The input file to read the OpenAPI definition from.
  • -l : The language to generate code in. I used Spring to generate Java based Spring framework code
  • -o : to specify the output directory i.e. generated code path

Lets check the output -o directory path to see genrated source code and import that projet in STS or eclipse or your favourite editor.

Thank You.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s