Skip to content
ADP
API Design PrincipleBETA

[ADP-359] 部分回應

指導原則

  • 應該(SHOULD)支援通過常見查詢參數進行結果欄位過濾: fields

    http
    GET /locations?fields=(name,id) HTTP/1.1
    GET /nations?fields=(fieldlevel1(fieldlevel2)) HTTP/1.1
    GET /results?fields=!tag
    GET /employees?fields=!(fieldlevel1(fieldlevel2), fieldlevel1_2)
  • 應該(SHOULD)返回 200 OK,因為 206 Partial Content 專門用於範圍請求。

BNF 規則

bnf
<fields>            ::= [ <negation> ] <fields_struct>
<fields_struct>     ::= "(" <field_items> ")"
<field_items>       ::= <field> [ "," <field_items> ]
<field>             ::= <field_name> | <fields_substruct>
<fields_substruct>  ::= <field_name> <fields_struct>
<field_name>        ::= <dash_letter_digit> [ <field_name> ]
<dash_letter_digit> ::= <dash> | <letter> | <digit>
<dash>              ::= "-" | "_"
<letter>            ::= "A" | ... | "Z" | "a" | ... | "z"
<digit>             ::= "0" | ... | "9"
<negation>          ::= "!"

範例

http
GET /jobs?fields=(name, id) HTTP/1.1

HTTP/1.1 200 OK
{
    jobs: [{
      id: 'uuid-',
      name: '...'
    }]
}

OpenAPI 3.1.0 範例

yaml
openapi: 3.1.0
info:
  title: 部分回應 API
  version: 1.0.0
paths:
  /jobs:
    get:
      summary: 獲取帶欄位過濾的工作
      parameters:
        - in: query
          name: fields
          schema:
            type: string
          description: 要包含在回應中的欄位
          example: "(name,id)"
      responses:
        '200':
          description: 成功回應
          content:
            application/json:    
              schema:
                type: object
                properties:
                  jobs:
                    type: array
                    items:
                      type: object
                      properties:
                        id:
                          type: string
                          format: uuid
                        name:
                          type: string
                required:
                  - jobs

components:
  parameters:
    FieldsParameter:
      name: fields
      in: query
      description: 要包含在回應中的欄位
      schema:
        type: string
      example: "(name,id)"

最佳實踐

  1. 對無效的欄位請求實施適當的錯誤處理。
  2. 在允許複雜欄位過濾時考慮性能影響。
  3. 在 API 文件中記錄支援的欄位和任何限制。
  4. 使用快取策略來提高頻繁請求的欄位組合的性能。

參考資料

Changelog

  • 2024.09.19 Remove outdated microsoft guideline link.