Willem's Fizzy Logic

Learn how to quickly generate REST clients from Open API Specification files

Learn how to quickly generate REST clients from Open API Specification files

Often when you work with REST endpoints the makers of these endpoints expose swagger (Open API Specification) files. Many developers however still handcode their clients. Not only is this bad, because you increase the chance that there will be bugs in the specification. It is inefficient as well. Here's a better way to generate your clients.

Method 1: Use the swagger editor

The most interactive way to create a client from a swagger file is using the online swagger editor. Go to https://editor.swagger.io/. Select file, import URL and type in the URL of the swagger endpoint you want to load.

Alternatively you can select File, Import File and upload the downloaded swagger.json file.

Next select Generate client and choose the language of your choice. The end result is a zip file you can download with the generated client code.

Method 2: Use the swagger-codegen application

I can imagine that you don't want to use the editor all the time, because that increases the chance for human error.

The code generator used in the swagger editor is the [swagger-codegen](https://swagger.io/tools/swagger-codegen/) application.

This is a Java application that does exactly the same thing as the editor, but through a commandline utility.

To use the swagger-codegen you need to perform the following steps:

  1. Clone the repository to disk git clone https://github.com/swagger-api/swagger-codegen.git
  2. Run mvn clean package
  3. Copy the swagger-codegen-cli.jar file from the target folder to a convient place on your computer. Preferrably place its location in the PATH variable.

Next execute the following command to generate a client:

java -jar swagger-codegen-cli.jar -i <json_file> -l python -o my_client

There are three arguments for this command:

There are many supported languages, I used python as an example, but you can generate clients for python, ruby, java, C#, scala and many more.

Enjoy!

For me using the codegenerator saved me a lot of time. I hope it does the same for you!

About

Willem Meints is a Chief AI Architect at Aigency/Info Support, bringing a wealth of experience in artificial intelligence and software development. As a Microsoft AI Most Valuable Professional (MVP), he has been recognized for his significant contributions to the AI community.

In addition to his professional work, Willem is an author dedicated to advancing the field of AI. His latest work focuses on effective applications of large language models, providing valuable guidance for professionals and enthusiasts alike.

Willem is a fan of good BBQ, reflecting his appreciation for craftsmanship both in and out of the digital realm.

Contact