Skip to content
ADP
API Design PrincipleBETA

[ADP-758] OpenAPI: $ref

概述

在 OpenAPI 規範中,有兩種主要方法可以引用可重用組件:

  1. 內部引用: 在同一 OpenAPI 文件中使用 #/components/*
  2. 外部引用: 使用託管在公共網站或項目存儲庫中的單獨 YAML 文件。

指導原則

示例:定義和使用內部引用

  • 定義組件:
yaml
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        email:
          type: string
  • 引用組件:
yaml
paths:
  /users:
    get:
      summary: 檢索所有用戶
      responses:
        '200':
          description: 用戶列表
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'

示例:定義和使用外部引用

  • 外部文件中的用戶架構 (https://example.com/openapi/schema.yaml):
yaml
User:
  type: object
  properties:
    id:
      type: string
    name:
      type: string
    email:
      type: string
  • 在主 OpenAPI 文件中引用外部架構:
yaml
openapi: 3.0.0
info:
  title: 用戶 API
  version: 1.0.0
paths:
  /users:
    get:
      summary: 檢索所有用戶
      responses:
        '200':
          description: 用戶列表
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: 'https://example.com/openapi/schema.yaml#/User'

組件類型

components 部分可以包含各種可重用元素:

架構

定義請求和回應主體中使用的數據模型。

yaml
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        email:
          type: string

回應

為常見的 HTTP 回應定義可重用的回應模板。

yaml
components:
  responses:
    NotFound:
      description: 未找到資源
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

參數

定義可重用的查詢參數、路徑參數、標頭等。

yaml
components:
  parameters:
    PageSize:
      name: pageSize
      in: query
      description: 每頁返回的結果數
      required: false
      schema:
        type: integer
        default: 10

示例

為請求主體、回應和參數提供示例以說明用法。

yaml
components:
  examples:
    UserExample:
      summary: 用戶示例
      value:
        id: '1'
        name: '張三'
        email: 'zhangsan@example.com'

請求主體

定義可重用的請求主體結構。

yaml
components:
  requestBodies:
    UserRequest:
      description: 要創建的用戶
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/User'

標頭

定義可重用的標頭。

yaml
components:
  headers:
    RateLimit:
      description: 當前期間允許的請求數
      schema:
        type: integer

安全方案

定義可重用的安全方案。

yaml
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key

相關 ADP

參考資料

INFO

💡 某些 OpenAPI 編輯工具不支持編輯 OpenAPI 文件的 #/components/parameters 屬性(property);此外,我們假設 OpenAPI 文件可能由業務單位/公司中的不同群組擁有/管理。