Swagger 高级功能
使用 components 复用定义
Schema(数据模型)复用
components 允许您定义可在整个 API 文档中重复使用的元素,减少重复并确保一致性:
实例
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
username:
type: string
email:
type: string
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
username:
type: string
email:
type: string
引用方式:
实例
paths:
/users/{id}:
get:
responses:
'200':
description: 用户信息
content:
application/json:
schema:
$ref: '#/components/schemas/User'
/users/{id}:
get:
responses:
'200':
description: 用户信息
content:
application/json:
schema:
$ref: '#/components/schemas/User'
Parameters(公共参数)复用
定义常用参数:
实例
components:
parameters:
PageParam:
name: page
in: query
schema:
type: integer
default: 1
description: 页码
LimitParam:
name: limit
in: query
schema:
type: integer
default: 10
description: 每页记录数
parameters:
PageParam:
name: page
in: query
schema:
type: integer
default: 1
description: 页码
LimitParam:
name: limit
in: query
schema:
type: integer
default: 10
description: 每页记录数
引用方式:
实例
paths:
/products:
get:
parameters:
- $ref: '#/components/parameters/PageParam'
- $ref: '#/components/parameters/LimitParam'
/products:
get:
parameters:
- $ref: '#/components/parameters/PageParam'
- $ref: '#/components/parameters/LimitParam'
Responses(通用响应)复用
定义标准响应:
实例
components:
responses:
NotFound:
description: 资源未找到
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 404
message:
type: string
example: "资源不存在"
BadRequest:
description: 请求参数错误
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 400
message:
type: string
responses:
NotFound:
description: 资源未找到
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 404
message:
type: string
example: "资源不存在"
BadRequest:
description: 请求参数错误
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 400
message:
type: string
引用方式:
实例
paths:
/users/{id}:
get:
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
$ref: '#/components/responses/NotFound'
'400':
$ref: '#/components/responses/BadRequest'
/users/{id}:
get:
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
$ref: '#/components/responses/NotFound'
'400':
$ref: '#/components/responses/BadRequest'
API 版本控制
通过 servers 区分版本
实例
servers:
- url: https://api.example.com/v1
description: API v1
- url: https://api.example.com/v2
description: API v2
- url: https://api.example.com/v1
description: API v1
- url: https://api.example.com/v2
description: API v2
通过路径区分版本
实例
paths:
/v1/users:
get:
# v1 用户接口...
/v2/users:
get:
# v2 用户接口...
/v1/users:
get:
# v1 用户接口...
/v2/users:
get:
# v2 用户接口...
通过请求头区分版本
实例
paths:
/users:
get:
parameters:
- name: api-version
in: header
required: true
schema:
type: string
enum: ['1.0', '2.0']
/users:
get:
parameters:
- name: api-version
in: header
required: true
schema:
type: string
enum: ['1.0', '2.0']
Mock 数据模拟
使用 examples 定义示例数据
在响应中定义示例:
实例
paths:
/users:
get:
responses:
'200':
description: 用户列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
examples:
userList:
summary: 样例用户列表
value:
- id: 1
username: "user1"
email: "user1@example.com"
- id: 2
username: "user2"
email: "user2@example.com"
/users:
get:
responses:
'200':
description: 用户列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
examples:
userList:
summary: 样例用户列表
value:
- id: 1
username: "user1"
email: "user1@example.com"
- id: 2
username: "user2"
email: "user2@example.com"
使用 Swagger UI Mock 功能
Swagger UI 集成了模拟服务器,可以基于您的 OpenAPI 定义生成模拟响应。
配置 mockServer 到 Swagger UI:
实例
SwaggerUI({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUI.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUI.plugins.MockPlugin
],
mockImplementations: {
'/users': {
get: () => ({
status: 200,
body: [
{ id: 1, name: "Test User 1" },
{ id: 2, name: "Test User 2" }
]
})
}
}
})
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUI.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUI.plugins.MockPlugin
],
mockImplementations: {
'/users': {
get: () => ({
status: 200,
body: [
{ id: 1, name: "Test User 1" },
{ id: 2, name: "Test User 2" }
]
})
}
}
})
使用第三方 Mock 服务
- Prism: OpenAPI 模拟服务器
- Mockoon: 可与 Swagger 集成的模拟 API 工具
- Postman: 提供 mock 服务器功能
高级安全配置
定义多种认证方法:
实例
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
apiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
OAuth2:
type: oauth2
flows:
implicit:
authorizationUrl: https://example.com/oauth/authorize
scopes:
read: 读取权限
write: 写入权限
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
apiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
OAuth2:
type: oauth2
flows:
implicit:
authorizationUrl: https://example.com/oauth/authorize
scopes:
read: 读取权限
write: 写入权限
应用安全定义:
实例
security:
- bearerAuth: []
- apiKeyAuth: []
paths:
/users:
get:
security:
- OAuth2: [read]
- bearerAuth: []
- apiKeyAuth: []
paths:
/users:
get:
security:
- OAuth2: [read]
文档分离与组织
使用 $ref 引用外部文件:
实例
paths:
/users:
$ref: './paths/users.yaml'
/products:
$ref: './paths/products.yaml'
components:
schemas:
User:
$ref: './schemas/user.yaml'
/users:
$ref: './paths/users.yaml'
/products:
$ref: './paths/products.yaml'
components:
schemas:
User:
$ref: './schemas/user.yaml'
标签与分组
使用标签组织 API 端点:
实例
tags:
- name: users
description: 用户管理
- name: products
description: 产品管理
paths:
/users:
get:
tags:
- users
/products:
get:
tags:
- products
- name: users
description: 用户管理
- name: products
description: 产品管理
paths:
/users:
get:
tags:
- users
/products:
get:
tags:
- products
扩展字段
通过 x- 前缀添加自定义属性:
实例
lpaths:
/users:
get:
x-controller: UserController
x-rate-limit: 100
x-deprecated: false
/users:
get:
x-controller: UserController
x-rate-limit: 100
x-deprecated: false
这些高级功能可以帮助您创建更加结构化、可维护和专业的 API 文档。
点我分享笔记