Generate client side code using Swagger Codegen

Overview

  • Swagger provides a simple, powerful representation for you APIs.
  • After creating an API what you need is a client side code to access the API.
  • Swagger provides an open source product to do that.

Swagger Codegen

  • Swagger codegen is the tool that we are going to use for generating client side code.
  • You can simple download swagger codegen from here.

Building Swagger Codegen

  • After downloading the source code from github, you need to build the product.
  • Since it’s maven project what you need to open the terminal there and build the product using the following command.

                     mvn package

Generating client side code

  • There are plenty of supported languages for swagger and i’ll go with JAVA.
  • Swagger needs YAML or JSON swagger file as the input.( The file that is used to represent the API using swagger.)
  • You can find a lot of sample json files from swagger and I’ll go with petstore example.
  • Writing JSON or YAML for swagger is tricky. You need to have clear idea about that. So please refer swagger  specification to get an idea.
  • You can use swagger editor to write your own swagger files using YAML or json.
  • Use the bellow command to generate the java client side code.
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate 
  -i http://petstore.swagger.io/v2/swagger.json 
  -l java 
  -o samples/client/petstore/java

How to use the generated client side code

  • Now all the hard part is done. Simply import the generated client side code into your preferred IDE.
  • You can find a package called io.swagger.client.api and there should be three classes.
  • Using these three classes you can do anything you want.
  • For and example let’s say that you need to update a pet and display his name. You can don that using the following lines.

Important

  • If your preferred language is not in the list you can simply create a new module by using the bellow command.

java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar meta -o output/myLibrary -n myClientCodegen -p com.my.company.codegen

  • Read this to get a more clear idea on swagger codegen.

 

 

 

 

 

5 Comments Add yours

  1. In swagger generated code apiInvoker.getInstance() is returning null.

    do you have any idea about it ?

    1. admin says:

      Did you use a properly written swagger file? 🙂

  2. Rob says:

    How do you also have code remarks/comments outputted also for classes, methods, properties and etc.,? I generated dynamic-html and it worked, but remarks/comments aren’t generated…

    Thanks

Leave a Reply