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 OpenAPI Generator to achieve this.
Some of the tools that could be used for this purpose are:
2. Java REST Client Application From Swagger File Using OpenAPI Generator
As we said, our focus will be on the OpenAPI Generator code generator. So, let's see how to do this.
First, we need to download OpenAPI Generator executable jar. It's available here.
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 openapi-generator-cli.jar generate -i http://petstore.swagger.io/v2/swagger.json --api-package com.javahowtos.petstore.client.api --model-package com.javahowtos.petstore.client.model --invoker-package com.javahowtos.petstore.client.invoker --group-id com.javahowtos --artifact-id openapi-generator-api-client --artifact-version 0.0.1-SNAPSHOT -g java -p java8=true --library resttemplate -o openapi-generator-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 - the programming language of generated client
-library - the generated project will use this library for rest calls
-o - the output directory – provided using
We can list all available generator parameters using the following command:
java -jar openapi-generator-cli.jar config-help -g java
3. Supported libraries
OpenAPI Generator provides support for the following Java libraries:
- Java (Feign)
- Java (Retrofit)
- Java (Retrofit2)
- Java (Jersey2)
- Java (okhttp-gson)
- Java (RestTemplate)
- Java (Spring 5 WebClient)
- Java (RESTEasy)
- Java (Vertx)
- Java (Google APIs Client Library)
- Java (Rest-assured)
- Java (Java 11 Native HTTP client)
- Java (Apache HttpClient)
For the purpose of this tutorial, we were using RestTemplate.
In this short tutorial, we demonstrated how to create a Java REST client for your application that exposes REST API using OpenAPI Generator. 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 Swagger Codegen.