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

Published 9/26/2018 7:53:20 AM
Filed under Developers life

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:

  • -i Specifies the path to the input file. This can be a URL
  • -l Specifies the programming language for the client
  • -o Specifies the output directory where the generate code should be located

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!