Generate Spring Boot REST Client with Swagger – 用Swagger生成Spring Boot REST客户端

最后修改: 2017年 9月 12日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this article, we’ll use the Swagger Codegen and OpenAPI Generator projects to generate REST clients from an OpenAPI/Swagger spec file.

在本文中,我们将使用Swagger CodegenOpenAPI Generator项目,从OpenAPI/Swagger spec文件生成REST客户端。

Also, we’ll create a Spring Boot project, where we’ll use generated classes.

另外,我们将创建一个Spring Boot项目,在那里我们将使用生成的类。

We’ll use the Swagger Petstore API example for everything.

我们将使用Swagger Petstore API实例来说明一切。

2. Generate REST Client With Swagger Codegen

2.用Swagger Codegen生成REST客户端

Swagger provides a utility jar that allows us to generate REST clients for various programming languages and multiple frameworks.

Swagger提供了一个实用的jar,使我们能够为各种编程语言和多种框架生成REST客户端。

2.1. Download Jar File

2.1.下载Jar文件

The code-gen_cli.jar can be downloaded from here.

code-gen_cli.jar可以从这里下载。

For the newest version, please check the swagger-codegen-cli repository.

关于最新的版本,请查看swagger-codegen-cli仓库。

2.2. Generate Client

2.2.生成客户端

Let’s generate our client by executing the command java -jar swagger-code-gen-cli.jar generate:

让我们通过执行java -jar swagger-code-gen-cli.jar generate:命令来生成我们的客户端。

java -jar swagger-codegen-cli.jar generate \
  -i http://petstore.swagger.io/v2/swagger.json \
  --api-package com.baeldung.petstore.client.api \
  --model-package com.baeldung.petstore.client.model \
  --invoker-package com.baeldung.petstore.client.invoker \
  --group-id com.baeldung \
  --artifact-id spring-swagger-codegen-api-client \
  --artifact-version 0.0.1-SNAPSHOT \
  -l java \
  --library resttemplate \
  -o spring-swagger-codegen-api-client

The provided arguments consist of:

提供的参数包括:。

  • A source swagger file URL or path – provided using the -i argument
  • Names of packages for generated classes – provided using –api-package, –model-package, –invoker-package
  • Generated Maven project properties –group-id, –artifact-id, –artifact-version
  • The programming language of the generated client – provided using -l
  • The implementation framework – provided using the –library
  • The output directory – provided using -o

To list all Java-related options, type the following command:

要列出所有与Java有关的选项,请输入以下命令。

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

Swagger Codegen supports the following Java libraries (pairs of HTTP clients and JSON processing libraries):

Swagger Codegen支持以下Java库(成对的HTTP客户端和JSON处理库)。

  • 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

In this write-up, we chose rest-template as it’s a part of the Spring ecosystem.

在这篇文章中,我们选择了rest-template,因为它是Spring生态系统的一部分。

3. Generate REST Client With OpenAPI Generator

3.用OpenAPI生成器生成REST客户端

OpenAPI Generator is a fork of Swagger Codegen capable of generating 50+ clients from any OpenAPI Specification 2.0/3.x documents.

OpenAPI Generator是Swagger Codegen的一个分叉,能够从任何OpenAPI规范2.0/3.x文档中生成50多个客户端。

Whereas Swagger Codegen is maintained by SmartBear, OpenAPI Generator is maintained by a community that includes more than 40 of the top contributors and template creators of Swagger Codegen as founding team members.

Swagger Codegen是由SmartBear维护的,而OpenAPI Generator是由一个社区维护的,其中包括40多个Swagger Codegen的顶级贡献者和模板创建者作为创始团队成员。

3.1. Installation

3.1.安装

Perhaps the easiest and most portable installation method is using the npm package wrapper, which works by providing a CLI wrapper atop the command-line options supported by the Java code. Installation is straightforward:

也许最简单、最便携的安装方法是使用npm包装器,它通过在Java代码支持的命令行选项之上提供一个CLI包装器来工作。安装是直接的。

npm install @openapitools/openapi-generator-cli -g

For those wanting the JAR file, it can be found in Maven Central. Let’s download it now:

对于那些想要JAR文件的人来说,可以在Maven中心找到。现在我们来下载它。

wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.3/openapi-generator-cli-4.2.3.jar \
  -O openapi-generator-cli.jar

3.2. Generate Client

3.2.生成客户

First, the options for OpenAPI Generator are almost identical to those for Swagger Codegen. The most notable difference is the replacement of the -l language flag with the -g generator flag, which takes the language to generate the client as a parameter.

首先,OpenAPI Generator的选项与Swagger Codegen的选项几乎相同。最明显的区别是将-l语言标志替换为-g生成器标志,后者将生成客户端的语言作为一个参数。

Next, let’s generate a client equivalent to the one we generated with Swagger Codegen using the jar command:

接下来,让我们使用jar命令生成一个相当于我们用Swagger Codegen生成的客户端。

java -jar openapi-generator-cli.jar generate \
  -i http://petstore.swagger.io/v2/swagger.json \
  --api-package com.baeldung.petstore.client.api \
  --model-package com.baeldung.petstore.client.model \
  --invoker-package com.baeldung.petstore.client.invoker \
  --group-id com.baeldung \
  --artifact-id spring-openapi-generator-api-client \
  --artifact-version 0.0.1-SNAPSHOT \
  -g java \
  -p java8=true \
  --library resttemplate \
  -o spring-openapi-generator-api-client

To list all Java-related options, type the command:

要列出所有与Java有关的选项,请输入命令。

java -jar openapi-generator-cli.jar config-help -g java

OpenAPI Generator supports all of the same Java libraries as Swagger CodeGen plus a few extra. The following Java libraries (pairs of HTTP clients and JSON processing libraries) are supported by OpenAPI Generator:

OpenAPI Generator支持所有与Swagger CodeGen相同的Java库,另外还有一些额外的。OpenAPI Generator支持以下Java库(成对的HTTP客户端和JSON处理库)。

  • jersey1 – Jersey1 + Jackson
  • jersey2 – Jersey2 + Jackson
  • feign – OpenFeign + Jackson
  • okhttp-gson – OkHttp + Gson
  • retrofit (Obsolete) – Retrofit1/OkHttp + Gson
  • retrofit2 – Retrofit2/OkHttp + Gson
  • resttemplate – Spring RestTemplate + Jackson
  • webclient – Spring 5 WebClient + Jackson (OpenAPI Generator only)
  • resteasy – Resteasy + Jackson
  • vertx – VertX + Jackson
  • google-api-client – Google API Client + Jackson
  • rest-assured – rest-assured + Jackson/Gson (Java 8 only)
  • native – Java native HttpClient + Jackson (Java 11 only; OpenAPI Generator only)
  • microprofile – Microprofile client + Jackson (OpenAPI Generator only)

4. Generate Spring Boot Project

4.生成Spring Boot项目

Let’s now create a new Spring Boot project.

现在让我们创建一个新的Spring Boot项目。

4.1. Maven Dependency

4.1.Maven的依赖性

We’ll first add the dependency of the Generated API Client library – to our project pom.xml file:

我们首先将生成的API客户端库的依赖关系添加到我们的项目pom.xml文件。

<dependency>
    <groupId>com.baeldung</groupId>
    <artifactId>spring-swagger-codegen-api-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

4.2. Expose API Classes as Spring Beans

4.2.将API类暴露为Spring Bean

To access the generated classes, we need to configure them as beans:

为了访问生成的类,我们需要把它们配置成Bean。

@Configuration
public class PetStoreIntegrationConfig {

    @Bean
    public PetApi petApi() {
        return new PetApi(apiClient());
    }
    
    @Bean
    public ApiClient apiClient() {
        return new ApiClient();
    }
}

4.3. API Client Configuration

4.3.API客户端配置

The ApiClient class is used for configuring authentication, the base path of the API, common headers, and it’s responsible for executing all API requests.

ApiClient类用于配置认证、API的基本路径、通用头文件,并负责执行所有API请求。

For example, if you’re working with OAuth:

例如,如果你正在使用OAuth。

@Bean
public ApiClient apiClient() {
    ApiClient apiClient = new ApiClient();

    OAuth petStoreAuth = (OAuth) apiClient.getAuthentication("petstore_auth");
    petStoreAuth.setAccessToken("special-key");

    return apiClient;
}

4.4. Spring Main Application

4.4.Spring的主应用程序

We need to import the newly created configuration:

我们需要导入新创建的配置。

@SpringBootApplication
@Import(PetStoreIntegrationConfig.class)
public class PetStoreApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(PetStoreApplication.class, args);
    }
}

4.5. API Usage

4.5.API的使用

Since we configured our API classes as beans, we can freely inject them in our Spring-managed classes:

由于我们将API类配置为Bean,我们可以自由地将它们注入Spring管理的类中。

@Autowired
private PetApi petApi;

public List<Pet> findAvailablePets() {
    return petApi.findPetsByStatus(Arrays.asList("available"));
}

5. Alternative Solutions

5.替代解决方案

There are other ways of generating a REST client other than executing Swagger Codegen or OpenAPI Generator CLI.

除了执行Swagger Codegen或OpenAPI Generator CLI,还有其他生成REST客户端的方法。

5.1. Maven Plugin

5.1.maven插件

A swagger-codegen Maven plugin that can be configured easily in your pom.xml allows generating the client with the same options as Swagger Codegen CLI.

swagger-codegen Maven插件可在您的pom.xml中轻松配置,允许以与Swagger Codegen CLI相同的选项生成客户端。

This is a basic code snippet that we can include in our project’s pom.xml to generate client automatically:

这是一个基本的代码片段,我们可以把它包含在我们项目的pom.xml中,以自动生成客户端。

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.3</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>swagger.yaml</inputSpec>
                <language>java</language>
                <library>resttemplate</library>
            </configuration>
        </execution>
    </executions>
</plugin>

5.2. Swagger Codegen Online Generator API

5.2.Swagger Codegen在线生成器API

An already published API that helps us with generating the client by sending a POST request to the URL http://generator.swagger.io/api/gen/clients/java passing the spec URL alongside with other options in the request body.

一个已经发布的API,通过向URL http://generator.swagger.io/api/gen/clients/java发送POST请求,在请求体中传递规格URL和其他选项,帮助我们生成客户端。

Let’s do an example using a simple curl command:

让我们用一个简单的curl命令做一个例子。

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 response would be JSON format that contains a downloadable link that contains the generated client code in zip format. You may pass the same options used in the Swaager Codegen CLI to customize the output client.

响应将是JSON格式,包含一个可下载的链接,其中包含生成的zip格式的客户端代码。你可以通过在Swaager Codegen CLI中使用的相同选项来定制输出的客户端。

https://generator.swagger.io contains a Swagger documentation for the API where we can check its documentation and try it.

https://generator.swagger.io包含了API的Swagger文档,在这里我们可以检查其文档并进行尝试。

5.3. OpenAPI Generator Online Generator API

5.3.OpenAPI生成器在线生成API

Like Swagger Godegen, OpenAPI Generator also has an online generator. Let’s perform an example using a simple curl command:

像Swagger Godegen一样,OpenAPI Generator也有一个在线生成器。让我们用一个简单的curl命令来执行一个例子。

curl -X POST -H "content-type:application/json" \
  -d '{"openAPIUrl":"http://petstore.swagger.io/v2/swagger.json"}' \
  http://api.openapi-generator.tech/api/gen/clients/java

The response, in JSON format, will contain a downloadable link to the generated client code in zip format. You may pass the same options used in the Swagger Codegen CLI to customize the output client.

响应为JSON格式,将包含一个可下载的链接,以zip格式生成客户端代码。你可以通过Swagger Codegen CLI中使用的相同选项来定制输出的客户端。

https://github.com/OpenAPITools/openapi-generator/blob/master/docs/online.md contains the documentation for the API.

https://github.com/OpenAPITools/openapi-generator/blob/master/docs/online.md包含了该API的文档。

6. Conclusion

6.结论

Swagger Codegen and OpenAPI Generator enable you to generate REST clients quickly for your API with many languages and with the library of your choice. We can generate the client library using a CLI tool, Maven plugin, or Online API.

Swagger Codegen和OpenAPI Generator使您能够用多种语言和您选择的库为您的API快速生成REST客户端。我们可以使用CLI工具、Maven插件或在线API生成客户端库。

This is a Maven-based project that contains three Maven modules: the generated Swagger API client, the generated OpenAPI client, and the Spring Boot application.

这是一个基于Maven的项目,包含三个Maven模块:生成的Swagger API客户端、生成的OpenAPI客户端,以及Spring Boot应用程序。

As always, you can find the code available over on GitHub.

一如既往,你可以在GitHub上找到可用的代码