Spring Boot中使用Swagger CodeGen生成REST client

Swagger是一个非常好用的API工具,我们会使用Swagger来暴露API给外界测试,那么有没有简单的办法来生成对应的调client呢?

Swagger CodeGen是一个REST 客户端生成工具,它可以从Open API的规范定义文件中生成对应的REST Client代码。本文我们将会举例说明如何通过OpenAPI 规范定义文件自动生成REST Client。

什么是Open API规范定义文件呢?

OpenAPI规范(OAS)为RESTful API定义了一个与语言无关的标准接口,使人类和计算机都可以发现和理解服务的功能,而无需访问源代码,文档或通过网络流量检查。 正确定义后,使用者可以使用最少的实现逻辑来理解远程服务并与之交互。

然后,文档生成工具可以使用OpenAPI定义来显示API,代码生成工具可以使用各种编程语言,测试工具和许多其他用例来生成服务器和客户端。

值得一提的是OpenAPI规范最早也是Swagger提出来的,后面被捐赠给了社区。

推荐的OpenAPI 文档名字通常为openapi.json 或者 openapi.yaml。

我们看一个swagger自带的 petstore open api 例子: 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"
}
}

我们可以看到在这个open API 定义文件里面包含了我们在swagger界面上看到的一切,paths,definitions等。

生成Rest Client

有了Open Api定义文件之后,我们就可以使用 swagger-codegen-cli 来生成对应的rest client文件了。

目前为止,最新的swagger-codegen-cli版本是2.4.12, 我们可以从这里下载 https://search.maven.org/classic/remotecontent?filepath=io/swagger/swagger-codegen-cli/2.4.12/swagger-codegen-cli-2.4.12.jar。

下载到本地之后,我们可以通过如下命令来生成rest client:

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

上述的参数包含:

  • -i 指定了open api 定义文件的地址
  • –api-package, –model-package, –invoker-package 指定了生成文件的package
  • –group-id, –artifact-id, –artifact-version 指定生成的maven 项目的属性
  • -l 指明生成的代码编程语言
  • –library 指定了实际的实现框架
  • -o 指定输出文件目录

Swagger Codegen 支持如下的Java 库:

  • 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

在Spring Boot中使用

我们把生成的代码拷贝到我们的Spring Boot项目中。然后通过下面的代码来启动应用程序:

@SpringBootApplication
public class GenerateClientApp { public static void main(String[] args) {
SpringApplication.run(GenerateClientApp.class, args);
} @Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
} }

我们再定义一个controller:

@RestController
public class PetController { @Autowired
private PetApi petApi; @GetMapping("/api/findAvailablePets")
public List<Pet> findAvailablePets() {
return petApi.findPetsByStatus(Arrays.asList("available"));
}
}

现在通过curl localhost:8080/api/findAvailablePets就可以远程调用http://petstore.swagger.io/v2/swagger.json 里面暴露的接口了。

API Client 配置

默认情况下ApiClient是默认的不需要认证的,如果需要认证,可以自定义ApiClient如下:

@Bean
public ApiClient apiClient() {
ApiClient apiClient = new ApiClient(); OAuth petStoreAuth = (OAuth) apiClient.getAuthentication("petstore_auth");
petStoreAuth.setAccessToken("special-key"); return apiClient;
}

使用Maven plugin

除了使用cli命令之外,我们还可以在pom中添加plugin来实现这个功能:

<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>

在线生成API

我们可以通过http://generator.swagger.io来在线生成API代码:

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

该命令会返回一个包含代码的zip包供你下载。

本文的例子可以参考 https://github.com/ddean2009/learn-springboot2/tree/master/springboot-generate-restclient

更多教程请参考 flydean的博客

Spring Boot中使用Swagger CodeGen生成REST client的更多相关文章

  1. spring boot中利用mybatis-generator插件生成代码

    使用Idea在spring boot中集成mybatis-generator,自动生成mapper.xml  model  dao 文件 一.配置 pom.xml 在pom.xml的<plugi ...

  2. Spring boot中使用springfox来生成Swagger Specification小结

    Rest接口对应Swagger Specification路径获取办法: 根据location的值获取api   json描述文件 也许有同学会问,为什么搞的这么麻烦,api json描述文件不就是h ...

  3. spring boot 中使用swagger 来自动生成接口文档

    1.依赖包 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swa ...

  4. Spring Boot 中使用 Swagger

    前后端分离开发,后端需要编写接⼝说明⽂档,会耗费⽐较多的时间. swagger 是⼀个⽤于⽣成服务器接⼝的规范性⽂档,并且能够对接⼝进⾏测试的⼯具. 作用 ⽣成接⼝说明⽂档 对接⼝进⾏测试 使用步骤 ...

  5. spring boot 中使用swagger

    一.pom.xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox ...

  6. 【swagger】1.swagger提供开发者文档--简单集成到spring boot中【spring mvc】【spring boot】

    swagger提供开发者文档 ======================================================== 作用:想使用swagger的同学,一定是想用它来做前后台 ...

  7. Spring Boot中使用Swagger2生成RESTful API文档(转)

    效果如下图所示: 添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <!-- https://mvnrepository.com/artifact/io.springfox ...

  8. Spring Boot中使用Swagger2构建API文档

    程序员都很希望别人能写技术文档,自己却很不愿意写文档.因为接口数量繁多,并且充满业务细节,写文档需要花大量的时间去处理格式排版,代码修改后还需要同步修改文档,经常因为项目时间紧等原因导致文档滞后于代码 ...

  9. Spring Boot中使用Swagger2构建RESTful APIs

    关于 Swagger Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因: Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API. S ...

随机推荐

  1. 手写一个Promise/A+,完美通过官方872个测试用例

    前段时间我用两篇文章深入讲解了异步的概念和Event Loop的底层原理,然后还讲了一种自己实现异步的发布订阅模式: setTimeout和setImmediate到底谁先执行,本文让你彻底理解Eve ...

  2. Unity 游戏框架搭建 2019 (二十五) 类的第一个作用 与 Obselete 属性

    在上一篇我们整理到了第七个示例,我们今天再接着往下整理.我们来看第八个示例: #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; ...

  3. Docker常用yml

    GitLib version: '3.1' services: web: image: 'twang2218/gitlab-ce-zh:11.0.5' restart: always hostname ...

  4. 1062 Talent and Virtue (25分)(水)

    About 900 years ago, a Chinese philosopher Sima Guang wrote a history book in which he talked about ...

  5. Docker多网卡

    # 查看所有网络 docker network ls # 如果要查看更加详细的虚拟网卡,如下指令 docker network inspect [NetWorkEthName | NetWorkEth ...

  6. (js描述的)数据结构[栈结构](2)

    (js描述的)数据结构[栈结构](2) 一.什么是栈结构 1.一种受限制的线性结构,这种结构可以基于数组来实现. 2.可以抽象成一个容器,上面的是栈顶,底下的是栈底.所以仅允许对栈顶进行操作, 二.栈 ...

  7. Struts2-学习笔记系列(14)-拦截器

    6.1对action 的拦截 自定义拦截器: public class MyInterceptor extends AbstractInterceptor { private String name; ...

  8. Struts2-学习笔记系列(10)-自定义类型转换

    注意name=user和对应action中的实例名称一致 这些代码是写在HTML文件中的 <s:form action="login"> <s:textfield ...

  9. Python设计模式(5)-代理模式

    # coding=utf-8 # 代理模式:# * 代理类成为实际想调用对象的中间件,可以控制对实际调用对象的访问权限# * 可以维护实际对象的引用 class DbManager: def __in ...

  10. lr事务

    事务:transaction(性能里面的定义:客户机对服务器发送请求,服务器做出反应的过程) 用于模拟用户的一个相对完整的业务操作过程:如登录,查询,交易等操作(每次http请求不会用来作为一个事务) ...