1. Introduction

In this short tutorial, we'll show how to generate a Java client application from Swagger file. There are multiple tools to achieve this, and here we'll show one where we use Swagger Codegen to achieve this.

Some of the tools that could be used for this purpose are: 

Swagger Codegen 

OpenAPI Generator

Swagger.io code generator feature

If you want to use 

2. Generate Java Client Application From Swagger File Using Swagger Codegen

As we said, our focus will be on the Swagger Codegen code generator. So, let's see how to do this.

The code-gen_cli.jar can be downloaded from this location. Pick the newest version available.

Let's generate our REST client by executing the jar file we downloaded. We'll need to pass some parameters to it, ie. the location of our Swagger file, some maven project parameters, and libraries we would like to have in generated code.

java -jar swagger-codegen-cli.jar generate
-i http://petstore.swagger.io/v2/swagger.json // swagger file location
--api-package com.javahowtos.petstore.client.api // name of api package
--model-package com.javahowtos.petstore.client.model // name of model package
--invoker-package com.javahowtos.petstore.client.invoker // name of invoker package
--group-id com.javahowtos // group id
--artifact-id codegen-api-client // artifact id
--artifact-version 0.0.1-SNAPSHOT // artifact version
-l java // language (this lib can be used for other languages also)
--library resttemplate // library for REST calls
-o codegen-api-client


Let's see what every argument is used for:

-i - source of Swagger file, could be URL or file path
-api-package, -model-package, -invoker-package - names of packages for specific components for generated project
-group-id, -artifact-id, -artifact-version - Maven project properties
-l - programming language of generated client
-library - generated project will use this library for rest calls
-o - the output directory

We can list all available generator parameters using the following command:

java -jar swagger-codegen-cli.jar config-help -l java

3. Supported libraries 


Swagger Codegen provides support for the following Java libraries:

  • Java (Feign)
  • Java (Retrofit)
  • Java (Retrofit2)
  • Java (Jersey2)
  • Java (okhttp-gson)
  • Java (RestTemplate)
  • Java (RESTEasy)
  • Java (Vertx)
  • Java (Google APIs Client Library)
  • Java (Rest-assured)

For the purpose of this tutorial, we were using RestTemplate.

4. Conclusion

In this short tutorial, we demonstrated how to create a Java REST client for your application that exposes REST API. If you want to try some other ways for code generation, you can check this tutorial where we show how to generate an application client with Swagger.io code generation feature, or this one where we'll use OpenAPI Generator.