3. API接口文档规范:OpenAPI/Swagger规范介绍、文档结构、请求/响应模型定义
3.1 OpenAPI/Swagger 规范概述
OpenAPI 规范(原 Swagger 规范)是业界标准的 RESTful API 接口描述语言,它定义了一套与编程语言无关的接口契约。通过 OpenAPI 文档,开发者可以清晰地了解 API 的端点、请求参数、响应结构以及认证方式,从而实现服务端与客户端之间的解耦与自动化工具链支持。
核心价值: OpenAPI 文档不仅是静态的接口说明书,更是驱动 API 网关、SDK 生成、Mock 服务、自动化测试和文档门户的单一事实来源(Single Source of Truth)。
| 特性 | Swagger 2.0 | OpenAPI 3.0 | OpenAPI 3.1 |
|---|---|---|---|
| 规范基础 | JSON Schema 草案 4 | JSON Schema 草案 7 | JSON Schema 2020-12 |
| 请求体定义 | body / formData |
requestBody 对象 |
同 3.0,增强多内容类型 |
| 响应描述 | responses 内联定义 |
responses + content 分离 |
同 3.0,支持 Webhooks |
| 安全方案 | securityDefinitions |
components/securitySchemes |
同 3.0,支持 OAuth 2.0 细化 |
| 示例与注释 | 有限支持 | example / examples |
增强 examples 多实例 |
3.2 文档结构:从根对象到路径
一个标准的 OpenAPI 文档由顶层对象开始,逐层展开。以下是最小化但完整的文档骨架:
openapi: "3.0.3"
info:
title: 日志检索准入门禁自助服务 API
description: 提供门禁权限的申请、审批、日志查询接口
version: "1.0.0"
contact:
name: API 支持团队
email: api-support@example.com
servers:
- url: https://api.example.com/v1
description: 生产环境
paths:
/access-requests:
post:
summary: 提交门禁权限申请
operationId: createAccessRequest
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/AccessRequest'
responses:
'201':
description: 申请创建成功
content:
application/json:
schema:
$ref: '#/components/schemas/AccessRequestResponse'
components:
schemas:
AccessRequest:
type: object
properties:
userId:
type: string
areaCode:
type: string
startTime:
type: string
format: date-time
endTime:
type: string
format: date-time
required:
- userId
- areaCode
- startTime
- endTime
AccessRequestResponse:
type: object
properties:
requestId:
type: string
status:
type: string
enum: [pending, approved, rejected]
createdAt:
type: string
format: date-time
文档层级速查:
- openapi — 规范版本号,必须位于根节点第一行。
- info — API 元信息(标题、版本、联系方式)。
- servers — 可用的服务器地址列表,支持变量替换。
- paths — 所有 API 端点的定义,按 HTTP 方法分组。
- components — 可复用的模型、参数、响应、安全方案等。
3.3 请求模型定义:参数与请求体
在 OpenAPI 中,请求参数分为三类:路径参数、查询参数、请求头参数,以及请求体(requestBody)。以下表格对比了它们的定义位置与使用场景:
| 参数类型 | 定义位置 | 示例 | 适用场景 |
|---|---|---|---|
| 路径参数 | path |
/users/{userId} |
标识唯一资源,如用户 ID、门禁区域编码 |
| 查询参数 | query |
?page=1&size=20 |
分页、过滤、排序条件 |
| 请求头参数 | header |
X-Request-Id |
幂等键、追踪 ID、内容类型协商 |
| 请求体 | requestBody |
JSON 对象 | 创建/更新资源时提交的复杂数据 |
避坑提示: 在 OpenAPI 3.0 中,
requestBody 必须显式声明 required: true 或 required: false。如果省略,工具默认视为非必填,可能导致客户端生成代码时遗漏必填校验。
3.4 响应模型定义:状态码与内容类型
每个 API 端点可以定义多个响应状态码,每个状态码下可指定返回的内容类型和对应的 Schema。推荐的做法是:
- 2xx 成功响应:返回业务数据实体。
- 4xx 客户端错误:返回统一的错误结构,包含错误码、消息和请求追踪 ID。
- 5xx 服务端错误:返回最小化错误信息,避免泄露内部细节。
responses:
'200':
description: 查询成功
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 0
message:
type: string
example: "success"
data:
type: array
items:
$ref: '#/components/schemas/AccessLog'
'400':
description: 请求参数错误
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
3.5 模型复用与 $ref 引用
当多个端点共享相同的数据结构时,应使用 $ref 引用 components/schemas 中定义的模型。这不仅能减少文档冗余,还能确保一致性。
最佳实践:
- 所有业务实体(如用户、门禁记录、审批单)都定义在
components/schemas中。 - 错误响应结构统一为
ErrorResponse,包含code、message、requestId字段。 - 分页查询的响应使用
PaginatedResponse泛型模式,包含items、total、page、size。 - 使用
allOf或oneOf处理多态模型,避免重复定义。
components:
schemas:
ErrorResponse:
type: object
properties:
code:
type: integer
description: 业务错误码
message:
type: string
description: 人类可读的错误描述
requestId:
type: string
description: 请求追踪 ID,用于日志关联
required:
- code
- message
PaginatedResponse:
type: object
properties:
items:
type: array
items:
type: object
total:
type: integer
page:
type: integer
size:
type: integer
3.6 文档工具链与自动化
基于 OpenAPI 规范的文档,可以无缝接入以下工具链:
| 工具 | 用途 | 输入 | 输出 |
|---|---|---|---|
| Swagger UI | 交互式 API 文档门户 | OpenAPI YAML/JSON | Web 页面 |
| Swagger Codegen | 生成客户端 SDK | OpenAPI YAML/JSON | Java、Python、Go 等代码 |
| OpenAPI Generator | 服务端 Stub 生成 | OpenAPI YAML/JSON | Spring Boot、Express 等 |
| Redoc | 静态 API 文档渲染 | OpenAPI YAML/JSON | HTML 文档 |
| Postman | API 调试与测试 | 导入 OpenAPI | 集合与测试脚本 |
推荐工作流: 在 CI/CD 流水线中集成 OpenAPI 规范校验(如 spectral),确保每次代码提交都生成合规的文档,并自动发布到 Swagger UI 或 Redoc 门户。