Skip to content
ADP
API Design PrincipleBETA

[ADP-321] 省略空值

指導原則

  • 雖然我們定義 null 跟空值有相同語意,應該(SHOULD) 在屬性為空或為null時省略可選屬性。

  • 必須(MUST)使用 OpenAPI 的 description 欄位來說明可選屬性何時存在或不存在的規則。

    yaml
    application/json:
      schema:
        type: object
        required: [id, name]
        properties:
          id:
            type: string
          name:
            type: string
          nickname:
            type: string
            description: "When the user is a guest, this field is optional."
            nullable: true
  • 不得(MUST NOT)為可選屬性包含null值。

    • 在少數情況下,需要處理未初始化狀況時,若 0/-1 都無法被用來指涉為未初始化狀態(已經有其他語意),可(MAY)使用null值,並在 description 欄位中說明。此時 null 並不代表此欄位為可選項。
    yaml
    application/json:
      schema:
        type: object
        properties:
          id:
            type: string
          temperature:
            type:
              - number
              - 'null'
            description: |
              The latest temperature reading in Celsius.
              If `null`, it indicates the sensor has not yet been initialized.
  • 應該考慮缺失屬性和明確設置為null值之間的語義差異。

範例

正確做法

json
{
  "paymentMethod": "INVOICE_SINGLE"
}

錯誤做法

json
{
  "paymentMethod": "INVOICE_SINGLE",
  "installments": null
}

Changelog

  • 2025.03.31: Add optional field description rule.