Swagger Codegen 在线生成器
swagger-generator
模块将 codegen 公开为 Web 服务,它有自己的基于 swagger-js
的 Web UI,并且提供 docker 镜像 swaggerapi/swagger-generator-v3
。
Web 服务部署在 https://generator3.swagger.io/ui,或者可以很容易地部署为 docker 容器。
生成器服务 API 的 OpenAPI 规范可通过 Web 服务公开的 UI(例如 https://generator3.swagger.io/ui)、公开的 YAML (https://generator3.swagger.io/openapi.json) 或源代码库(https://github.com/swagger-api/swagger-codegen/blob/3.0.0/modules/swagger-generator/src/main/resources/openapi.yaml)获得。
请注意,通过提供属性
codegenVersion
(例如"codegenVersion" : "v3"
),支持 V2(用于 v2 规范)和 V3 生成器(用于在生成期间转换的 v3 和 v2 规范)。
例如,要生成 Java API 客户端,只需使用 curl 发送以下 HTTP 请求
1curl -X POST \2 https://generator3.swagger.io/api/generate \3 -H 'content-type: application/json' \4 -d '{5 "specURL" : "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml",6 "lang" : "java",7 "type" : "CLIENT",8 "codegenVersion" : "V3"9}'
响应将包含一个包含生成代码的 zip 文件。
要自定义 SDK,可以使用以下 HTTP 正文指定特定于语言的选项
1{2 "specURL" : "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml",3 "lang" : "java",4 "options" : {5 "additionalProperties" : {6 "useRuntimeException": true,7 "useRxJava" : true8 }9 },10 "type" : "CLIENT",11 "codegenVersion" : "V3"12}
其中可以通过向 https://generator3.swagger.io/api/options?language={language}&version={codegenVersion}
提交 GET
请求来获得一种语言的 options
additionalProperties
例如,curl https://generator3.swagger.io/api/options?language=java&version=V3
返回(截断的输出)
1{2 "sortParamsByRequiredFlag": {3 "opt": "sortParamsByRequiredFlag",4 "description": "Sort method arguments to place required parameters before optional parameters.",5 "type": "boolean",6 "default": "true"7 },8 "ensureUniqueParams": {9 "opt": "ensureUniqueParams",10 "description": "Whether to ensure parameter names are unique in an operation (rename parameters that are not).",11 "type": "boolean",12 "default": "true"13 },14 "allowUnicodeIdentifiers": {15 "opt": "allowUnicodeIdentifiers",16 "description": "boolean, toggles whether unicode identifiers are allowed in names or not, default is false",17 "type": "boolean",18 "default": "false"19 },20 "modelPackage": {21 "opt": "modelPackage",22 "description": "package for generated models",23 "type": "string"24 },25 ...
除了使用带有 OpenAPI/Swagger 规范 URL 的 specURL
之外,还可以使用 spec
将规范包含在 JSON 有效负载中,例如
1{2 "options": {},3 "spec": {4 "swagger": "2.0",5 "info": {6 "version": "1.0.0",7 "title": "Test API"8 },9 ...10 }11}