Swagger是一套用于设计、构建、文档化和使用RESTful API的强大工具集。在Linux环境下使用Swagger时,以下技巧可以帮助你提高效率:
# 使用Docker安装Swagger Editor
docker pull swaggerapi/swagger-editor
docker run -d -p 8080:8080 swaggerapi/swagger-editor
# 或者使用npm安装本地版本
npm install -g swagger-editor
swagger-editor
# 下载最新版本
wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.34/swagger-codegen-cli-3.0.34.jar -O swagger-codegen-cli.jar
# 创建别名方便使用
alias swagger-codegen='java -jar /path/to/swagger-codegen-cli.jar'
Ctrl+Alt+S
(Windows/Linux) 或 Cmd+Alt+S
(Mac) 预览Swagger文档# 使用锚点和别名减少重复定义
definitions:
User:
type: object
properties:
id: &id_field
type: integer
format: int64
name: &name_field
type: string
email:
type: string
format: email
Admin:
type: object
properties:
admin_id: *id_field
admin_name: *name_field
privileges:
type: array
items:
type: string
# 生成Java客户端
swagger-codegen generate -i api.yaml -l java -o ./client/java
# 生成TypeScript客户端
swagger-codegen generate -i api.yaml -l typescript-angular -o ./client/angular
# 下载默认模板
swagger-codegen author template -o ./templates -l typescript-angular
# 使用自定义模板生成代码
swagger-codegen generate -i api.yaml -l typescript-angular -t ./templates -o ./client/custom
# 使用Docker运行Swagger UI
docker pull swaggerapi/swagger-ui
docker run -p 8081:8080 -e SWAGGER_JSON=/foo/api.yaml -v /path/to/your/api:/foo swaggerapi/swagger-ui
# 或者使用npm安装
npm install -g swagger-ui
swagger-ui -p 8080 -w api.yaml
# 使用Node.js项目中的swagger-ui-express
npm install swagger-ui-express --save
# 在Express应用中添加
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./api.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
# 使用swagger-cli验证
npm install -g @apidevtools/swagger-cli
swagger-cli validate api.yaml
# 使用openapi-validator
npm install -g ibm-openapi-validator
lint-openapi api.yaml
# 使用Dredd进行API测试
npm install -g dredd
dredd api.yaml http://localhost:3000
servers:
- url: "{protocol}://{host}:{port}/api/v1"
variables:
protocol:
enum:
- http
- https
default: https
host:
default: api.example.com
port:
enum:
- "80"
- "443"
- "8080"
default: "443"
# 主文件
paths:
/users:
$ref: "./paths/users.yaml"
/products:
$ref: "./paths/products.yaml"
# 使用swagger-cli合并
swagger-cli bundle api.yaml -o bundled-api.yaml
# 使用sed预处理文档
sed "s/{{VERSION}}/1.0.0/g" api-template.yaml > api.yaml
这些技巧可以帮助你在Linux环境下更高效地使用Swagger工具集,从API设计到文档生成,再到客户端代码创建和API测试,全面提升你的API开发工作流程。