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. A 【NOIP2012 day2】疫情控制

    时间限制 : 20000 MS   空间限制 : 128000 KB 评测说明 : 2s,128m 问题描述 H 国有 n 个城市,这 n 个城市用 n-1 条双向道路相互连通构成一棵树,1 号城市是 ...

  2. EEPROM存储芯片24C02

    1.24C02简介 24C02是一个2Kbit的串行EEPROM存储芯片,可存储256个字节数据.工作电压范围为1.8V到6.0V,具有低功耗CMOS技术,自定时擦写周期,1000000次编程/擦除周 ...

  3. git 为什么要先commit,然后pull,最后再push?而不是commit然后直接push?

    情况是这样的,现在远程有一个仓库,分支就一个,是master.然后我本地的仓库是从远程的master上clone下来的.大家都是clone下来,再在自己本地改好,再commit然后pull然后push ...

  4. JS必看面试题

    https://www.jianshu.com/p/f1f39d5b2a2e 1. javascript的typeof返回哪些数据类型. 答案:string,boolean,number,undefi ...

  5. JVM 理解性学习(二)

    1.G1 垃圾回收器 G1 能更少的 "Stop the World" ,能同时对新生代老年代进行垃圾回收. G1 将 Java 堆内存拆分为多个大小相等的 Region,并且新生 ...

  6. go 内存优化

    一.斐波那切数列优化 package main import ( "time" "fmt" ) const LIM = 41 var fibs [LIM]uin ...

  7. json === dict

    import requests import json ''' json.loads(json_str) json字符串转换成字典 json.dumps(dict) 字典转换成json字符串 ''' ...

  8. "按钮"组件:<h-button> —— 快应用组件库H-UI

     <import name="h-button" src="../Common/ui/h-ui/basic/c_button"></impo ...

  9. java nio消息半包、粘包解决方案

    问题背景 NIO是面向缓冲区进行通信的,不是面向流的.我们都知道,既然是缓冲区,那它一定存在一个固定大小.这样一来通常会遇到两个问题: 消息粘包:当缓冲区足够大,由于网络不稳定种种原因,可能会有多条消 ...

  10. Ant概念

    Ant是基于Java的.可以跨平台的项目编译和生成工具.