跳到内容

Swagger Codegen 生成器

如果默认生成器配置不满足您的需求,您有多种选项可以修改或创建新的模块或模板。

修改客户端库格式

不喜欢默认的 swagger 客户端语法?想要支持不同的语言?没问题!Swagger Codegen 使用 jmustache 引擎处理 mustache 模板。您可以修改我们的模板或创建您自己的模板。

您可以查看 modules/swagger-codegen/src/main/resources/${your-language} 获取示例。要制作您自己的模板,请创建您自己的文件并使用 -t 标志指定您的模板文件夹。就这么简单。

制作您自己的 codegen 模块

如果您正在启动一个新语言的项目,并且没有找到您需要的东西,Swagger Codegen 可以帮助您创建一个项目来生成您自己的库

终端窗口
1
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar meta \
2
-o output/myLibrary -n myClientCodegen -p com.my.company.codegen

这将在 output/myLibrary 文件夹中写入您开始所需的所有文件,包括一个 README.md。修改并编译后,您可以使用 codegen 加载您的库,并使用您自己定制的逻辑生成客户端。

然后,您可以在 output/myLibrary 文件夹中使用 mvn package 编译您的库,并像这样执行 codegen

终端窗口
1
java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.SwaggerCodegen

对于 Windows 用户,您需要在类路径中使用 ; 而不是 :,例如:

终端窗口
1
java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar;modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.SwaggerCodegen

请注意,myClientCodegen 现在是一个选项,您可以使用常用参数来生成您的库

终端窗口
1
java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar \
2
io.swagger.codegen.SwaggerCodegen generate -l myClientCodegen\
3
-i https://petstore.swagger.io/v2/swagger.json \
4
-o myClient

另请参阅 独立生成器开发

从本地文件生成客户端

如果您不想调用您的服务器,可以将 OpenAPI 规范文件保存到目录中,并像这样将参数传递给代码生成器

终端窗口
1
-i ./modules/swagger-codegen/src/test/resources/2_0/petstore.json

非常适合在 CI 服务器上,从 Swagger 编辑器… 或者在飞机上编码时创建库 ✈️。

忽略文件格式

Swagger Codegen 支持 .swagger-codegen-ignore 文件,类似于您可能已经熟悉的 .gitignore.dockerignore 文件。

--skip-overwrite 标志相比,忽略文件可以更好地控制覆盖现有文件。通过忽略文件,您可以指定要忽略的单个文件或目录。这可能很有用,例如,如果您只想生成代码的一个子集。

示例

终端窗口
1
# Swagger Codegen Ignore
2
# Lines beginning with a # are comments
3
4
# This should match build.sh located anywhere.
5
build.sh
6
7
# Matches build.sh in the root
8
/build.sh
9
10
# Exclude all recursively
11
docs/**
12
13
# Explicitly allow files excluded by other rules
14
!docs/UserApi.md
15
16
# Recursively exclude directories named Api
17
# You can't negate files below this directory.
18
src/**/Api/
19
20
# When this file is nested under /Api (excluded above),
21
# this rule is ignored because parent directory is excluded by previous rule.
22
!src/**/PetApiTests.cs
23
24
# Exclude a single, nested file explicitly
25
src/IO.Swagger.Test/Model/AnimalFarmTests.cs

.swagger-codegen-ignore 文件必须存在于输出目录的根目录中。

首次代码生成时,您还可以传递 CLI 选项 --ignore-file-override=/path/to/ignore_file,以更好地控制生成的输出。请注意,这是一个完全覆盖,在重新生成代码时将覆盖输出目录中的 .swagger-codegen-ignore 文件。

IntelliJ 中通过 .ignore 插件提供对 .swagger-codegen-ignore 文件的编辑器支持。

© . All rights reserved.