Skip to content
ADP
API Design PrincipleBETA

[ADP-760] OpenAPI: Webhooks

概述

Webhook 是一種廣泛使用的模式,用於透過 HTTP 端點在應用程式之間傳遞通知。本規範提供在 OpenAPI 中實作 webhook 的指導方針,並整合了 CloudEvents 規範的最佳實踐。

指導原則

安全要求

  • 必須(MUST)使用 HTTPS (HTTP-over-TLS) 進行所有 webhook 連接
  • 必須(MUST)實作以下其中一種授權方法:
    • Authorization 標頭中的 Bearer token
    • Basic Authentication(當對方僅提供此方式時)
    • Signature-based authentication
  • 不得(MUST NOT)使用基於挑戰的身份驗證方案
  • 應該(SHOULD)實作濫用防護機制:
    • 訂閱時的驗證握手
    • 使用 Retry-After 標頭進行速率限制
    • 使用 WebHook-Request-Origin 標頭進行來源驗證

Webhook 定義

  • 必須(MUST)使用 OpenAPI 3.1.0 或更高版本來定義 webhooks
  • 必須(MUST)使用 OpenAPI 文件中的 webhooks 部分
  • 必須(MUST)使用 POST 方法進行 webhook 傳遞
  • 必須(MUST)包含 Content-Type 標頭和負載(不允許空負載)
  • 不得(MUST NOT)跟隨 HTTP 重定向(3xx 回應)

回應處理

  • 必須(MUST)適當處理以下狀態碼:
    • 200/201:成功處理且包含負載
    • 204:成功處理但無負載
    • 202:已接受但尚未處理
    • 410:端點已停用
    • 415:不支援的媒體類型
    • 429:超過速率限制(包含 Retry-After 標頭)

文件要求

  • 必須(MUST)記錄:
    • 身份驗證要求和方法
    • 預期的請求/回應負載
    • 速率限制策略
    • 必要的標頭
  • 應該(SHOULD)包含範例負載和回應
  • 應該(SHOULD)描述重試策略和錯誤處理

示例

yaml
openapi: 3.1.0
info:
  title: Webhook 示例
  version: 1.0.0

webhooks:
  newPet:
    post:
      summary: 關於新寵物的資訊
      description: |
        當系統添加新寵物時觸發的 webhook。
        - 需要 HTTPS
        - 速率限制為每分鐘 100 請求
        - 包含 WebHook-Request-Origin 標頭用於驗證
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewPetPayload'
      parameters:
        - in: header
          name: WebHook-Request-Origin
          required: true
          schema:
            type: string
          description: 識別發送系統的 DNS 名稱
      responses:
        '200':
          description: Webhook 已成功處理
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookResponse'
        '202':
          description: Webhook 已接受,正在處理中
        '429':
          description: 超過速率限制
          headers:
            Retry-After:
              schema:
                type: integer
              description: 重試前需等待的秒數

components:
  schemas:
    NewPetPayload:
      type: object
      required:
        - id
        - name
        - timestamp
      properties:
        id:
          type: string
          format: uuid
          description: 寵物的唯一識別碼
        name:
          type: string
          description: 寵物名稱
        timestamp:
          type: string
          format: date-time
          description: 寵物建立時間
    WebhookResponse:
      type: object
      properties:
        status:
          type: string
          enum: [success, partial, error]
        message:
          type: string

  securitySchemes:
    webhookAuth:
      type: http
      scheme: bearer
      description: |
        Webhook 身份驗證的 Bearer token。
        Token 必須包含在以下其中之一:
        - Authorization 標頭
        - 'token' 查詢參數

參考資料

更新紀錄

  • 2025-03-07:根據 CloudEvents 規範更新並詳細說明安全要求。