Swagger 第一个文档

从零写一份能跑起来的用户接口规范,并在 Swagger Editor 里验证。

Beginner
Key Points先写 info + servers + 一个 GET 路径,再补 schema;每改一次就看 Editor 右侧的实时预览有没有报错。

第一步:最小可运行

YAML
openapi: 3.0.3
info:
  title: User API
  version: 1.0.0
  description: 一个用来练手的用户服务
servers:
  - url: https://api.example.com/v1
paths:
  /users:
    get:
      summary: 用户列表
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id:
                      type: integer
                    name:
                      type: string

第二步:补请求参数

YAML
    get:
      summary: 用户列表
      parameters:
        - name: page
          in: query
          description: 页码,从 1 开始
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: size
          in: query
          description: 每页条数
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
      responses:
        '200':
          description: 成功

第三步:抽出 schema

YAML
components:
  schemas:
    User:
      type: object
      required: [id, name]
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
          example: Alice
        email:
          type: string
          format: email
          example: alice@example.com
    UserList:
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/User'
        total:
          type: integer
        page:
          type: integer
        size:
          type: integer

校验

Red errors in the Swagger Editor mean the structure is invalid. Validate in CI as well; --fail-on-warnings makes style issues fail the build too.

Bash
# 用 swagger-cli 校验(Node)
npx @apidevtools/swagger-cli validate openapi.yaml

# 或用 spectral 做规范 + 风格检查
npx @stoplight/spectral-cli lint openapi.yaml --fail-severity warn
Common trap: quote the responses keys ('200'). Unquoted, YAML parses them as integers and some tools either fail or silently drop the entry.

Friends & Partners