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. 原生js判断手机端页面滚动停止

    var topValue = 0,// 上次滚动条到顶部的距离 interval = null;// 定时器 contactsList = document.getElementById(" ...

  2. C 怪兽游戏

    时间限制 : - MS   空间限制 : - KB  评测说明 : 1s,256m 问题描述 何老板在玩一款怪兽游戏.游戏虽然简单,何老板仍旧乐此不疲.游戏一开始有N只怪兽,编号1到N.其中第i只怪兽 ...

  3. 面试官:JavaScript 原始数据类型 Symbol 有什么用?

    以前提到 JavaScript 原始数据类型时,我们知道有Number,String,Null,Boolean,Undefined这几种.ES6 引入了新的基本数据类型Symbol和BigInt.今天 ...

  4. 关于C#三层架构增删改查中的“添加”问题

    关于“添加”功能的实现比较简单: 先来一个简单的界面: 然后是代码: ··采用的是三层架构的思想写的·· 在DAO中的方法为: (使用了动软自动生成代码) 希望对您有所帮助!

  5. Flask(python web) 处理表单和Ajax请求

    1.处理表单(form) 首先,编一个简单的html登录页面(名字为login.html(根路由jinjia2模板指定)): <html> <head> <meta ch ...

  6. 搭建react项目(低配版)

    react项目低配版,可作为react相关测试的基础环境,方便快速进行测试. git clone git@github.com:whosMeya/simple-react-app.git git ch ...

  7. GitHub搭建个人主页

    GitHub搭建个人主页 1.注册登录GitHub 2.新建仓库 新建一个名为"username.github.io",其中username为你的用户名,仓库必须为公有类型,私有仓 ...

  8. 字典树&&AC自动机---看完大概应该懂了吧。。。。

    目录 字典树 AC自动机 字典树 又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种.典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计 ...

  9. 你知道如何自动保存 Spring Boot 应用进程号吗

    1. 前言 欢迎阅读 Spring Boot 2 实战 系列文章. PID 对于系统运维来说并不陌生,但是对于一些开发者特别是新手还是要简单介绍一下的.它是 Process ID 的简称,是系统分配给 ...

  10. stand up meeting 11/24/2015

    part 组员 今日工作 工作耗时/h 明日计划 计划耗时/h 词典接口及数据转换 冯晓云 规范在线查词的各项请求,将返回结果解析成树状,并定义完成各种操作以方便其他部分完成调用,排序,增删等操作 3 ...