以下是在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
)。關鍵工具:
參考來源: