Skip to content
ADP
API Design PrincipleBETA

[ADP-755] OpenAPI: operationId

概述

什麼是operationId?

operationId 是OpenAPI文件中操作的唯一標識符。它用於識別特定操作,便於在客戶端庫、代碼生成工具和文件中進行更好的管理和引用。

指導原則

  • 應該(SHOULD)在OpenAPI文件中為每個API端點提供operationId。

    TIP

    operationId 值可以在API文件中用作錨點(anchor),並在生成的代碼中用作函數名稱。

  • 必須(MUST)在整個API中使用一致的命名約定。本原則推薦使用camelCase

    TIP

    大寫策略可能(MAY)會受到您的團隊、組織或應用程序的特定定義的影響。

  • 應該(SHOULD)選擇描述操作執行的動作的名稱。例如,getUsercreateOrderdeleteProduct清楚地表明了操作的目的。
  • 必須(MUST)避免使用不添加有意義資訊的冗餘前綴或後綴。例如,getUser優於userGet
  • 應該(SHOULD)確保operationId反映API中操作的上下文。例如,在管理圖書館的API中,borrowBookreturnBook提供了清晰的上下文。
  • 可以(MAY)在必要時在operationId中包含受眾資訊以避免衝突。例如,getUserForPublicExternalgetUserForComponentInternal
  • DRAFT 為了一致性,必須(MUST)在 operationId 中包含以下關鍵字:
    • get
    • list
    • update
    • delete
    • create
    • replace
    • add
    • set
    • unset
    • check
    • add (跟 create 不同,主要把子資源加到主資源)
    • remove (跟 delete 不同,主要把子資源從主資源移除)
  • DRAFT 根據以下情景使用適當動詞
Operation VerbRequestStatus CodeoperationIdDescription
getGET /users/{id}200getUserById檢索用戶
listGET /users200getUsers列出用戶列表
createPOST /orders201createOrder創建新訂單
updatePUT /users/{id}200updateUser更新用戶資訊
deleteDELETE /users/{id}204deleteUser刪除用戶
createPOST /users201createUser創建新用戶
replacePATCH /users/{id}200replaceUser替換用戶資訊
addPOST /orders/{id}/items201addItemToOrder向訂單添加項目
setPUT /orders/{id}/items/{itemId}200setOrderItem設置訂單項目
unsetDELETE /orders/{id}/items/{itemId}204unsetOrderItem移除訂單項目
checkGET /orders/{id}/items200checkOrderItems檢查訂單項目
addPOST /users/{id}/roles201addUserRole向用戶添加角色
removeDELETE /users/{id}/roles/{roleId}204removeUserRole從用戶中移除角色
  • 特定操作可以(MAY)不符合已定義的慣例。通常是類似 gRPC 的動作搭配 POST 方法。

示例

以下是一個OpenAPI文件片段的示例,其中正確定義了operationId值:

yaml
paths:
  /users:
    get:
      summary: 檢索用戶列表
      operationId: getUsers
      responses:
        '200':
          description: 用戶列表
  /users/{id}:
    get:
      summary: 通過ID檢索用戶
      operationId: getUserById
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: 用戶對象
  /orders:
    post:
      summary: 創建新訂單
      operationId: createOrder
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Order'
      responses:
        '201':
          description: 訂單已創建

相關ADPs

參考資料

Changelog

  • 2024.09.30: Add operation keywords
  • 2024.10.17: Add operationId usage tip