使用Swagger Codegen生成接口代码
Swagger Codegen简介
Swagger是用于Restful API接口生成的有力工具。通过Swagger和Spring Boot的集成,可以自动生成接口文档的html页面。除Html页面外,Swagger还会生成一个json的接口描述文件。有了这个描述文件,可以利用Swagger的Codegen工具生成接口调用代码。
Swagger Codegen是Swagger官方的代码生成工具,其网址是 https://swagger.io/tools/swagger-codegen/ ,在github中也有源码分支:https://github.com/swagger-api/swagger-codegen。
本质上,swagger codegen是一个java的命令行工具。目前它可以支持多种语言和开发框架的客户端接口调用代码的生成,其中包括:
- ActionScript,
- Ada,
- Apex,
- Bash,
- C# (.net 2.0, 3.5 or later),
- C++ (cpprest, Qt5, Tizen),
- Clojure,
- Dart,
- Elixir,
- Elm,
- Eiffel,
- Erlang,
- Go,
- Groovy,
- Haskell (http-client, Servant),
- Java (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured),
- Kotlin,
- Lua,
- Node.js (ES5, ES6, AngularJS with Google Closure Compiler annotations)
- Objective-C,
- Perl,
- PHP,
- PowerShell,
- Python,
- R,
- Ruby,
- Rust (rust, rust-server),
- Scala (akka, http4s, swagger-async-httpclient),
- Swift (2.x, 3.x, 4.x),
- Typescript (Angular1.x, Angular2.x, Fetch, jQuery, Node)
Swagger Codegen的使用
Swagger Codegen需要Java 7或8的运行环境支持。
下载 Swagger Codegen
wget http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.4.8/swagger-codegen-cli-2.4.8.jar -O swagger-codegen-cli.jar
当前Swagger Codegen有两个独立分支版本v2和v3
- v2 支持Swagger/OpenAPI version 2
- v3 支持OpenAPI version 3
运行Swagger Codegen命令行
# 显示帮助
java -jar swagger-codegen-cli.jar help
# The most commonly used swagger-codegen-cli commands are:
# config-help Config help for chosen lang
# generate Generate code with chosen lang
# help Display help information
# langs Shows available langs
# meta MetaGenerator. Generator for creating a new template set and configuration for Codegen. The output will be based on the language you specify, and includes default templates to include.
# validate Validate specification
# version Show version information
#
# See 'swagger-codegen-cli help <command>' for more information on a specific
# command.
# 显示可以支持的语言
java -jar swagger-codegen-cli.jar langs
# Available languages: [ada, ada-server, akka-scala, android, apache2, apex, aspnetcore, bash, csharp, clojure, cwiki, cpprest, csharp-dotnet2, dart, dart-jaguar, elixir, elm, eiffel, erlang-client, erlang-server, finch, flash, python-flask, go, go-server, groovy, haskell-http-client, haskell, jmeter, jaxrs-cxf-client, jaxrs-cxf, java, inflector, jaxrs-cxf-cdi, jaxrs-spec, jaxrs, msf4j, java-pkmst, java-play-framework, jaxrs-resteasy-eap, jaxrs-resteasy, javascript, javascript-closure-angular, java-vertx, kotlin, lua, lumen, nancyfx, nodejs-server, objc, perl, php, powershell, pistache-server, python, qt5cpp, r, rails5, restbed, ruby, rust, rust-server, scala, scala-gatling, scala-lagom-server, scalatra, scalaz, php-silex, sinatra, slim, spring, dynamic-html, html2, html, swagger, swagger-yaml, swift4, swift3, swift, php-symfony, tizen, typescript-aurelia, typescript-angular, typescript-inversify, typescript-angularjs, typescript-fetch, typescript-jquery, typescript-node, undertow, ze-ph, kotlin-server]
# 执行生成指令,生成angular的程序
java -jar swagger-codegen-cli.jar generate \
-i http://172.18.6.134:11005/v2/api-docs \
-l typescript-angular \
-o ./tmp
编写服务代码的注意事项
由于swagger codegen在生成客户端代码时依赖接口描述(对于spring boot swagger-ui来说就是api-docs的json文档),需要对controller的注解多加注意。
- 使用@ApiModel注解时,不要用中文定义value,否则codegen可能无法生成变量的类型名称;如果需客户端看到中文注释,可使用descriiption。例如:
@ApiModel(description = "材料图片类")
public class ProductImg{
@ApiModelProperty(notes = "材料图片")
private String src;
@ApiModelProperty(notes = "是否默认显示", required = true)
private int isDefault;
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public int getIsDefault() {
return isDefault;
}
public void setIsDefault(int isDefault) {
this.isDefault = isDefault;
}
}
- 使用@ApiModelProperty可以控制类型属性的生成,默认情况下类型属性为非必须,所以生成的typescript代码都会带?,这可以用required=true;另外可通过value或Notes生成属性的注释(建议使用notes)。上面的java类生成的typescript代码如下:
/**
* 材料图片类
*/
export interface ProductImg {
/**
* 是否默认显示
*/
isDefault: number;
/**
* 材料图片
*/
src?: string;
}
- Codegen默认会生成带controller后缀名的service类,可以通过@Api注解的tags属性修改,例如:
@CrossOrigin
@RestController()
@RequestMapping(value = Constants.URI_API_PREFIX + Constants.URI_BRAND)
@Api(description = "供应商接口服务", tags = { "Brand" })
public class BrandController {
@Autowired
private BrandService brandService;
@Autowired
private UserTokenService tokenService;
@ApiOperation(value = "getById", nickname = "getById", notes = "获取指定供应商", response = BrandResult.class)
@GetMapping(value = "/{brandId}", produces = "application/json")
public Result<Brand> getById(@PathVariable int brandId) {
return Result.success(brandService.getById(brandId));
}
}
@Api的description不会影响Codegen,但会在swagger-ui的html页面生成接口的注释
- Codegen会根据json文档中的operationId生成接口的方法名,默认情况下方法名是带UsingGET或UsingPost后缀的,可通过指定@ApiOperation的nickname对其进行指定(见上例)。上面java代码生成的typescript类如下:
/**
* 材料库接口API
* 用于材料库相关等信息
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent } from '@angular/common/http';
import { CustomHttpUrlEncodingCodec } from '../encoder';
import { Observable } from 'rxjs/Observable';
import { BrandResult } from '../model/brandResult';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable()
export class BrandService {
protected basePath = 'https://localhost:11005';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
this.basePath = basePath || configuration.basePath || this.basePath;
}
}
/**
* @param consumes string[] mime-types
* @return true: consumes contains 'multipart/form-data', false: otherwise
*/
private canConsumeForm(consumes: string[]): boolean {
const form = 'multipart/form-data';
for (const consume of consumes) {
if (form === consume) {
return true;
}
}
return false;
}
/**
* getById
* 获取指定供应商
* @param brandId brandId
* @param authorization 令牌
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getById(brandId: number, authorization?: string, observe?: 'body', reportProgress?: boolean): Observable<BrandResult>;
public getById(brandId: number, authorization?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<BrandResult>>;
public getById(brandId: number, authorization?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<BrandResult>>;
public getById(brandId: number, authorization?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
if (brandId === null || brandId === undefined) {
throw new Error('Required parameter brandId was null or undefined when calling getById.');
}
let headers = this.defaultHeaders;
if (authorization !== undefined && authorization !== null) {
headers = headers.set('Authorization', String(authorization));
}
// to determine the Accept header
let httpHeaderAccepts: string[] = [
'application/json'
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAcceptSelected != undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
];
return this.httpClient.get<BrandResult>(`${this.basePath}/api/material-bank/brand/${encodeURIComponent(String(brandId))}`,
{
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
}
- 范型类型在swagger显示中会有问题,如果是List, Set, Map等可通过@ApiOperation的responseContainer来指定封装,但如果是自定义的范型类,则需要定义一个扩展类。例如:
@ApiModel(description = "产品分页列表")
public class ProductPagedList extends PagedList<ProductSimple> {
}
然后在接口的@ApiOperation的response指定,例如:
@ApiOperation(value = "根据类别获取材料", response = ProductPagedListResult.class)
@PostMapping(value = "/search", produces = "application/json")
public Result<PagedList<ProductSimple>> search(@RequestBody SearchParam searchParam,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "12") int pageSize) {
return Result.success(productService.search(searchParam, page, pageSize));
}