跳转到内容

Openapi文档编写规范

Swagger 文档的编写与维护


[Requirement] OpenAPI 文档必须包含 openapi(版本,固定 3.0.3 或 3.1.0)、info(标题、版本、描述)、servers、paths、components 五大块。

[Standard] info.version 使用语义化版本(如 1.2.0),与代码发布版本对齐;info.description 需包含认证方式、基础 URL、错误码约定说明。

openapi: 3.1.0
info:
  title: 用户服务 API
  version: 1.2.0
  description: |
    用户中心服务接口文档。
    - 认证:Bearer Token(见 /auth/login)
    - 基础路径:https://api.example.com/api/v1
    - 错误码:见《错误码规范》,0=成功
  contact:
    name: 用户中心团队
    email: user-team@example.com
servers:
  - url: https://api.example.com/api/v1
    description: 生产环境
  - url: https://staging-api.example.com/api/v1
    description: 预发环境

[Standard] 按业务模块拆分 path 文件,通过 $ref 引用主文档,避免单文件过大。

openapi/
├── openapi.yaml # 主文档(info/servers/components)
├── paths/
│ ├── users.yaml
│ └── orders.yaml
├── schemas/
│ ├── user.yaml
│ └── order.yaml
└── responses/
└── common.yaml

[Requirement] 每个 operation 必须包含:summary(一句话功能)、operationId(唯一标识)、parameters/requestBody、responses。

[Standard] operationId 使用 {资源}_{动作} 小驼峰,如 getUser、createUser、listUsers。

[Standard] tags 按业务模块分组(如 Users、Orders),用于文档 UI 分类。

paths:
  /users/{userId}:
    get:
      tags: [Users]
      summary: 获取用户详情
      description: 根据用户 ID 查询用户信息,需登录态。
      operationId: getUser
      parameters:
        - name: userId
          in: path
          required: true
          schema: { type: integer, example: 1001 }
          description: 用户 ID
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema: { $ref: '#/components/schemas/UserResponse' }

[Requirement] 每个参数必须标注 required、type、description;枚举值列出所有可能值及含义。

[Standard] 参数描述需包含取值范围、默认值、是否敏感(如 password 标注 format: password)。

parameters:
  - name: status
    in: query
    required: false
    schema:
      type: string
      enum: [active, disabled, pending]
      default: active
    description: |
      用户状态过滤:
      - active:启用
      - disabled:禁用
      - pending:待审核

[Requirement] 每个 operation 至少声明 200(成功)和默认错误响应;有鉴权的必须声明 401、403。

[Standard] 通用响应(401/403/404/500)抽取到 components/responses 复用。

components:
  responses:
    Unauthorized:
      description: 未认证
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }

[Requirement] 所有 Schema 在 components/schemas 中定义并命名,禁止内联大对象;Schema 名使用大驼峰(PascalCase)。

[Standard] 请求体与响应体分开定义:UserCreateRequest、UserResponse,不复用同一 Schema。

components:
  schemas:
    UserResponse:
      type: object
      required: [id, name, created_at]
      properties:
        id:
          type: integer
          example: 1001
        name:
          type: string
          example: 张三
        email:
          type: string
          format: email
          example: zhang@example.com
        created_at:
          type: string
          format: date-time
          example: '2026-10-14T08:30:00Z'

[Standard] 为字段添加约束:minLength/maxLength、minimum/maximum、pattern、format,与代码校验逻辑保持一致。

[Caution] 禁止仅写 type: object 而不定义 properties,导致文档无字段说明。

[Standard] 抽取通用信封结构与错误结构。

components:
  schemas:
    ApiResponse:
      type: object
      required: [code, message, data, trace_id]
      properties:
        code: { type: integer, example: 0 }
        message: { type: string, example: ok }
        data: { type: object, nullable: true }
        trace_id: { type: string }
    ErrorResponse:
      allOf:
        - $ref: '#/components/schemas/ApiResponse'
        - type: object
          properties:
            errors:
              type: array
              items:
                type: object
                properties:
                  field: { type: string }
                  message: { type: string }

[Requirement] 每个请求体和响应体 Schema 必须提供 example 或 examples,且示例数据真实可读(不用 string、123 占位)。

[Standard] 多场景示例使用 examples 命名区分(如 success、partial)。

requestBody:
  required: true
  content:
    application/json:
      schema: { $ref: '#/components/schemas/UserCreateRequest' }
      examples:
        normal:
          summary: 普通用户
          value: { name: 张三, email: zhang@example.com, age: 28 }
        with_org:
          summary: 带组织
          value: { name: 李四, email: li@example.com, org_id: 5 }

[Caution] 示例禁止使用真实手机号、身份证、邮箱;使用公认占位(如 13800138000、user@example.com)。

[Standard] 时间示例使用具体日期,金额示例标注单位。


[Requirement] OpenAPI 文档由代码注解/装饰器自动生成(FastAPI 自动生成 / SpringDoc / Swagger Annotations),禁止手写后与代码脱节。

[Standard] CI 中校验文档与代码 Schema 一致性,不一致则流水线失败。

[Standard] 接口变更必须更新 info.version 并在文档中维护变更记录(Changelog)。

info:
  version: 1.3.0
  x-changelog:
    - version: 1.3.0
      date: '2026-10-01'
      changes: ['POST /users 新增可选字段 org_id']
    - version: 1.2.0
      date: '2026-09-01'
      changes: ['GET /users 支持 cursor 分页']

[Standard] 废弃接口在 operation 上标注 deprecated: true,并在 description 中写明替代接口与下线日期。

/users:
  get:
    deprecated: true
    summary: (已废弃)获取用户列表,请使用 GET /v2/users
    description: 将于 2026-04-01 下线,替代接口 GET /api/v2/users。

[Standard] 生产环境不对外暴露 Swagger UI;仅在内网/预发环境提供 /docs、/redoc,生产只暴露 /openapi.json 供内部工具使用。

[Caution] 禁止在文档中泄漏内部服务地址、数据库表名、密钥等敏感信息。