Install and generate source code for OpenAPI specs using OpenAPI Generator CLI

After you define API specs using OpenAPI, to implement these APIs using the programming language you are working with, you can use the Open API Generator CLI tool at https://github.com/OpenAPITools/openapi-generator to generate source code for that language. All we have left to do is add code to handle business logic for these APIs. In this tutorial, I will guide you on how to install this OpenAPI Generator CLI tool and try using it to generate code for the Spring framework using an example API specs!

Installation

First, this tool is written in Java, so please install Java on your computer.

To install OpenAPI Generator CLI, go to its Maven Repository at https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/, find its latest version. At the time I wrote this article, the latest version of OpenAPI Generator CLI was 7.15.0.

Then download the .jar file!

After downloading, in the folder containing the downloaded file, you can check the version of OpenAPI Generator CLI using the java command as follows:

For example, I run this command as follows:

Here, because I removed the version in the jar file, you can’t see the version in the command!

Result:

So we have successfully installed OpenAPI Generator!

Now I will try to use the “generate” command of OpenAPI Generator CLI to generate source code!

Generate source code

The syntax of this “generate” command is as follows:

The “-i” parameter is used to declare the path to the API specs file.

The “-g” parameter is used to define the generator name that you want to use to generate source code. The generator name will define the library or framework that OpenAPI Generator CLI uses to generate source code. OpenAPI Generator CLI supports many different programming languages ​​such as C, C++, Java frameworks, … And it also supports generating source code for the server side and client side! For a detailed list of generators that OpenAPI Generator CLI supports, you can see the details here https://openapi-generator.tech/docs/generators/.

The “-o” parameter is used to define the directory that will contain the source code that will be generated.

For example, I will use an API specs that I have defined on my GitHub here https://github.com/khanhnguyenj/student-management-openapi-specs.

I have cloned this repo to local, now I will use the following command to generate source code, as follows:

As you can see, I will use the generator name “spring” to generate source code for the Spring framework.

The result when I run the above command is as follows:

So we have successfully generated the source code.

Open the generated project, you will see the result similar to mine as follows:

Add Comment