Article Directory
Generating REST client using Swagger CodeGen in Spring Boot
Swagger is a very useful API tool. We will use Swagger to expose the API for external testing. Is there an easy way to generate corresponding client s?
Swagger CodeGen is a REST client generation tool that generates corresponding REST Client code from the specification definition file of the Open API.In this article, we will provide an example of how to automatically generate a REST Client from an OpenAPI specification definition file.
What is an Open API specification definition file?
The OpenAPI specification (OAS) defines a language-independent standard interface for the RESTful API that enables people and computers to discover and understand the capabilities of services without access to source code, documentation, or network traffic checks.Once properly defined, users can use the least implementation logic to understand and interact with remote services.
Document generation tools can then use OpenAPI definitions to display APIs, code generation tools can use a variety of programming languages, test tools, and many other use cases to generate servers and clients.
It is worth mentioning that the OpenAPI specification was first introduced by Swagger and later donated to the community.
The recommended OpenAPI document name is usually openapi.json or openapi.yaml.
Let's look at an example of the petstore open api that comes with swagger: https://petstore.swagger.io/v2/swagger.json
{ "swagger": "2.0", "info": { "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", "version": "1.0.3", "title": "Swagger Petstore", "termsOfService": "http://swagger.io/terms/", "contact": { "email": "apiteam@swagger.io" }, "license": { "name": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html" } }, "host": "petstore.swagger.io", "basePath": "/v2", "tags": [ ... ], "schemes": [ "https", "http" ], "paths": { ... "definitions": { ... }, "externalDocs": { "description": "Find out more about Swagger", "url": "http://swagger.io" } }
We can see that this open API definition file contains everything we see on the swagger interface, paths, definitions, and so on.
Generate Rest Client
With the Open Api definition file, we can use swagger-codegen-cli to generate the rest client file.
So far, the latest version of swagger-codegen-cli is 2.4.12, from which we can download https://search.maven.org/classic/remotecontent?filepath=io/swagger/swagger-codegen-cli/2.4.12/swagger-codegen-cli-2.4.12.jar.
Once downloaded locally, we can generate rest client s with the following commands:
java -jar swagger-codegen-cli-2.4.12.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ --api-package com.flydean.client.api \ --model-package com.flydean.client.model \ --invoker-package com.flydean.client.invoker \ --group-id com.flydean \ --artifact-id springboot-generate-restclient \ --artifact-version 0.0.1-SNAPSHOT \ -l java \ --library resttemplate \ -o springboot-generate-restclient
The above parameters include:
- -i specifies the address of the open api definition file
- - api-package, - model-package, - invoker-package specifies the package of the generated file
- - group-id, - artifact-id, - artifact-version specifies the properties of the generated maven project
- -l Indicates the generated code programming language
- - library specifies the actual implementation framework
- -o Specify output file directory
Swagger Codegen supports the following Java libraries:
- jersey1 – Jersey1 + Jackson
- jersey2 – Jersey2 + Jackson
- feign – OpenFeign + Jackson
- okhttp-gson – OkHttp + Gson
- retrofit (Obsolete) – Retrofit1/OkHttp + Gson
- retrofit2 – Retrofit2/OkHttp + Gson
- rest-template – Spring RestTemplate + Jackson
- rest-easy – Resteasy + Jackson
Use in Spring Boot
We copy the generated code into our Spring Boot project.Then start the application with the following code:
@SpringBootApplication public class GenerateClientApp { public static void main(String[] args) { SpringApplication.run(GenerateClientApp.class, args); } @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
Let's define another controller:
@RestController public class PetController { @Autowired private PetApi petApi; @GetMapping("/api/findAvailablePets") public List<Pet> findAvailablePets() { return petApi.findPetsByStatus(Arrays.asList("available")); } }
The exposed interface in http://petstore.swagger.io/v2/swagger.json can now be called remotely via curl localhost:8080/api/findAvailablePets.
API Client Configuration
By default, ApiClient is the default and does not require authentication. If authentication is required, you can customize ApiClient as follows:
@Bean public ApiClient apiClient() { ApiClient apiClient = new ApiClient(); OAuth petStoreAuth = (OAuth) apiClient.getAuthentication("petstore_auth"); petStoreAuth.setAccessToken("special-key"); return apiClient; }
Use Maven plugin
In addition to using the cli command, we can add plugin s to the pom to do this:
<build> <plugins> <plugin> <groupId>io.swagger</groupId> <artifactId>swagger-codegen-maven-plugin</artifactId> <version>2.4.12</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>swagger.json</inputSpec> <language>java</language> <library>resttemplate</library> </configuration> </execution> </executions> </plugin> </plugins> </build>
Online Generation API
We can generate API code online from http://generator.swagger.io:
curl -X POST -H "content-type:application/json" \ -d '{"swaggerUrl":"http://petstore.swagger.io/v2/swagger.json"}' \ http://generator.swagger.io/api/gen/clients/java
The command returns a zip package containing the code for you to download.
Examples of this article can be referenced https://github.com/ddean2009/learn-springboot2/tree/master/springboot-generate-restclient
Refer to more tutorials Fldean's Blog