在實務中,當 API 回傳的資料量很大(例如:上千筆使用者、幾萬筆商品),
我們不能一次把所有資料都丟回去,這會造成:
分頁的目標是: 一次只回傳使用者需要的部分資料。
使用 page 和 limit(或 offset 和 limit)。
GET /users?page=2&limit=10
代表:取第 2 頁,每頁 10 筆。
使用「游標(cursor)」記錄位置,例如某個 id。
GET /users?cursor=12&limit=10
代表:從 id = 12 之後取 10 筆資料。
排序的目標是: 讓使用者決定資料的呈現順序 。
GET /users?sort=created_at -> 按照 created_at 遞增排序
GET /users?sort=-created_at -> - 代表遞減排序
或用明確參數:
GET /users?sort=created_at&order=desc
一個實務 API 的範例:
GET /products?page=3&limit=20&sort=price&order=asc
回應範例:
{
"page": 3,
"limit": 20,
"total": 250,
"data": [
{ "id": 41, "name": "Keyboard", "price": 20 },
{ "id": 42, "name": "Mouse", "price": 22 }
]
}