Swagger 高级功能

oneOf/anyOf 组合、discriminator 多态、callbacks、links、示例与多文件拆分。

Advanced
Key Points组合用 allOf 继承、oneOf 表达互斥多态(配 discriminator);callbacks 描述回调,links 描述响应到下一步的关联。

allOf:继承与合并

YAML
components:
  schemas:
    Base:
      type: object
      required: [id]
      properties:
        id: { type: integer }
    User:
      allOf:
        - $ref: '#/components/schemas/Base'
        - type: object
          required: [name]
          properties:
            name: { type: string }

oneOf + discriminator:多态

oneOf means exactly one branch matches. With discriminator, tools pick the model from a type field instead of trying each branch.

YAML
components:
  schemas:
    Payment:
      oneOf:
        - $ref: '#/components/schemas/CardPayment'
        - $ref: '#/components/schemas/WalletPayment'
      discriminator:
        propertyName: method
        mapping:
          card: '#/components/schemas/CardPayment'
          wallet: '#/components/schemas/WalletPayment'
    CardPayment:
      type: object
      required: [method, cardNo]
      properties:
        method: { type: string }
        cardNo: { type: string }
    WalletPayment:
      type: object
      required: [method, walletId]
      properties:
        method: { type: string }
        walletId: { type: string }

callbacks:描述回调

YAML
paths:
  /payments:
    post:
      summary: 发起支付
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Payment'
      callbacks:
        onPaid:
          '{$request.body#/callbackUrl}':
            post:
              requestBody:
                content:
                  application/json:
                    schema:
                      type: object
                      properties:
                        paymentId: { type: integer }
                        status: { type: string }
              responses:
                '200':
                  description: 回调已接收

links:从响应串到下一步

YAML
responses:
  '201':
    description: 已创建
    links:
      GetUser:
        operationId: getUser
        parameters:
          id: '$response.body#/id'

多文件拆分

Past a few hundred lines, split it: keep info/servers/paths in the root and move schemas into components/schemas/*.yaml. Bundle into a single file before publishing.

Bash
npx @redocly/cli bundle openapi.yaml -o dist/openapi.bundled.yaml
Bundle in CI after splitting; otherwise broken $refs only show up after deployment.

示例的写法

YAML
content:
  application/json:
    schema:
      $ref: '#/components/schemas/User'
    examples:
      normal:
        summary: 普通用户
        value: { id: 42, name: Alice, status: active }
      disabled:
        summary: 已禁用
        value: { id: 43, name: Bob, status: disabled }

Friends & Partners