Skip to content
ADP
API Design PrincipleBETA

[ADP-706] null 和缺失(absent)的語義

指導原則

  • 必須(MUST)對 null 和缺失屬性具有相同的語義

如果一個屬性是 可為空的非必需的,則具有 null 值的屬性和缺失的屬性必須被視為語義上等同。

例如,以下兩個 JSON 對象應被視為語義上等同:

json
{
  "name": "John",
  "age": null
}
json
{
  "name": "John"
}

TIP

💡 PATCH 端點是此規則的一個例外(參見 必須正確使用 HTTP 方法)。參考上面的例子,使用第一個對象的 PATCH 請求會將 name 設置為 John 並將 age 設置為 null,而使用第二個對象的請求只會修改 name

  • Boolean 欄位絕不(MUST NOT)為 null 值。

  • 具有 null 值的欄位應該(SHOULD)被省略。

  • 空陣列和空物件不應(SHOULD NOT)能為null(應該使用[]或{}代替)。

null-indicating-unset

  • 當設計一個值來表示 未設定,且 0/'' 的意義不同於 未設定 值時,你可以(MAY)使用 null,並指定該字段為可為 null(OAI3.0)或可能為 null(OAI3.1)。建議(SHOULD)在 API 文件中記錄這點(null 表示 unset)。
    • 關於 未設定 的行為應該(SHOULD)在整個專案中保持一致。

INFO

如果真的必要設計出一個可為 null 的欄位,參考下方。

實現細節

這涉及 OpenAPI 規範中的 nullable 屬性(在 3.0 版本中,這由 nullable 屬性(property)表示,而在 3.1 版本中,這是通過在可能類型的數組中包含 null 來實現)以及模式中屬性(property)的 required 屬性。

OpenAPI 3.0 示例

yaml
openapi: 3.0.3
info:
  title: 示例 API
  version: 1.0.0
paths:
  /example:
    get:
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  name:
                    type: string
                  age:
                    type: integer
                    nullable: true
                required:
                  - name

OpenAPI 3.1 示例

yaml
openapi: 3.1.0
info:
  title: 示例 API
  version: 1.0.0
paths:
  /example:
    get:
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  name:
                    type: string
                  age:
                    type: [integer, null]
                required:
                  - name

參考

設計參考

Changelog

  • 2024.11.04: Add more null semantic
  • 2024.11.15: Add unset semantic