以下是在Linux上使用Swagger设计API数据模型的步骤:
安装Swagger工具
docker pull swaggerapi/swagger-editor # 编辑器
docker pull swaggerapi/swagger-ui # 可视化文档
docker run -d -p 8080:8080 swaggerapi/swagger-editor # 运行编辑器
sudo apt install nodejs npm
npm install -g swagger-editor # 安装编辑器
定义数据模型
swagger.yaml或swagger.json文件,使用components.schemas定义模型:components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
address:
$ref: '#/components/schemas/Address' # 嵌套模型引用
Address:
type: object
properties:
street:
type: string
city:
type: string
集成到API设计
paths:
/users/{id}:
get:
summary: 获取用户信息
parameters:
- name: id
in: path
required: true
type: integer
responses:
'200':
description: 用户详情
schema:
$ref: '#/components/schemas/User'
测试与文档化
高级功能(可选)
swagger-codegen工具根据模型生成后端代码(如Python、Java)。springfox-swagger2依赖)或Express(使用swagger-jsdoc)。关键工具:
参考来源: