[ADP-312] 分頁
reviewing phase 1
更正 OpenAPI 範例
概述
RESTful API 中的分頁是一種將大型數據集分割成更小、更易管理的塊或"頁面"的技術。這有助於提高性能、減少服務器負載並提供更好的用戶體驗。
分頁主要有兩種方法:基於偏移的分頁和基於游標的分頁。
基於偏移的分頁
基於偏移的分頁使用偏移值來指定數據集的起始點,並使用限制來指定要檢索的項目數。
示例
http
GET /resources?offset=20&limit=10 HTTP/1.1
http
HTTP/1.1 200 OK
Content-Type: application/json
Link: </resources?offset=20&limit=10>; rel="self", </resources?offset=30&limit=10>; rel="next", </resources?offset=10&limit=10>; rel="prev", </resources?offset=0&limit=10>; rel="first", </resources?offset=90&limit=10>; rel="last"
X-Total-Count: 100
{
"resources": [ /* 從偏移量20到29的資源 */ ]
}
基於游標的分頁
基於游標的分頁使用游標(通常是唯一標識符)來獲取下一組結果。
示例
http
GET /resources?cursor=abc123&limit=10 HTTP/1.1
http
HTTP/1.1 200 OK
Content-Type: application/json
Link: </resources?cursor=abc123&limit=10>; rel="self", </resources?cursor=def456&limit=10>; rel="next"
X-Total-Count: 256
{
"resources": [ /* 從游標abc123之後開始的資源 */ ]
}
指導原則
應該(SHOULD)選擇分頁約定並使用常見的查詢參數進行分頁。目前基於游標的分頁更為常見。
應該(SHOULD)使用常見的查詢參數(query parameters)來做分頁,即:
cursor
,offset
,limit
。應該(SHOULD)使用標準的 Link 標頭根據 RFC 8288 提供分頁資訊,而非在回應主體中嵌入連結。
httpHTTP/1.1 200 OK Content-Type: application/json Link: </resources?cursor=abc123&limit=10>; rel="self", </resources?cursor=def456&limit=10>; rel="next", </resources?cursor=xyz789&limit=10>; rel="prev", </resources?cursor=first&limit=10>; rel="first", </resources?cursor=last&limit=10>; rel="last" X-Total-Count: 256 { "resources": [ /* 資源項目 */ ] }
應該(SHOULD)使用自定義標頭來提供額外的分頁 metadata,例如總數量。這些標頭必須(MUST)在組織的內部註冊表中註冊。
X-Total-Count
: 可用項目的總數X-Page-Count
: 可用頁面的總數X-Current-Page
: 當前頁碼
示例
OpenAPI 示例
yaml
openapi: 3.1.0
info:
title: 示例 API
version: 1.0.0
paths:
/resources:
get:
summary: 獲取資源列表
parameters:
- name: cursor
in: query
description: 分頁的游標
required: false
schema:
type: string
- name: limit
in: query
description: 每頁項目數
required: false
schema:
type: integer
default: 20
maximum: 100
- name: filter
in: query
description: 過濾條件
required: false
schema:
type: string
- name: sort
in: query
description: 排序順序
required: false
schema:
type: string
responses:
'200':
description: 分頁的資源列表
headers:
Link:
description: 遵循 RFC 8288 的分頁連結
schema:
type: string
example: </resources?cursor=def456&limit=10>; rel="next", </resources?cursor=xyz789&limit=10>; rel="prev"
X-Total-Count:
description: 可用項目的總數
schema:
type: integer
example: 256
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
type: object
參考
規範參考
設計參考
更新紀錄
2025-04-14
: 更新為建議使用標準 Link 標頭和自定義標頭來提供分頁元數據,而非在回應主體中嵌入連結。