[ADP-313] 排序
reviewing phase 1
將 sort 加入共用 components.parameters
指導原則
- 必須(MUST)在 API 文件上記錄 API 對排序的支援。
- 必須(MUST)使用通用查詢參數
sort
。 - 必須(MUST)使用
-
來表示降序排序。默認情況下無符號表示升序。 - 必須(MUST)使用逗號分隔的列表來表示多個排序條件以及優先序。
- 應該(SHOULD)為所有集合資源支援排序。
- 應該(SHOULD)限制可排序的欄位數量以防止效能問題。
設計考慮
- URL 中的
+
會被編碼,所以我們省略升序的符號。 - 考慮允許多欄位排序時的效能影響。
- 請在文件上記錄當未提供
sort
參數時的默認排序行為為何。
範例
獲取應用程式列表,按
appName
升序(A 到 Z)然後按releaseDate
降序排序:httpGET /applications?sort=appName,-releaseDate
按姓氏(升序)然後按年齡(降序)對使用者排序:
httpGET /users?sort=lastName,-age
OpenAPI 3.1.0 範例
yaml
openapi: 3.1.0
info:
title: 範例 API
description: 用於演示排序的範例 API
version: 1.0.0
paths:
/applications:
get:
summary: 獲取應用程式列表
parameters:
- name: sort
in: query
description: 對應用程式列表進行排序
schema:
type: string
example: appName,-releaseDate
required: false
responses:
'200':
description: 應用程式列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Application'
/users:
get:
summary: 獲取使用者列表
parameters:
- name: sort
in: query
description: 對使用者列表進行排序
schema:
type: string
example: lastName,-age
required: false
responses:
'200':
description: 使用者列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
Application:
type: object
properties:
appName:
type: string
releaseDate:
type: string
User:
type: object
properties:
lastName:
type: string
age:
type: integer
實現細節
- 實現伺服器端排序以確保不同客戶端請求的結果一致。
- 對常用於排序的資料庫欄位使用適當的索引以優化查詢效能。
- 優雅地處理無效的排序參數,返回 400 Bad Request 並附帶清晰的錯誤訊息。
相關 ADP
- [ADP-311] 過濾
- [ADP-312] 分頁