# REST API 最佳实践
## URL 结构
### 资源命名
# 推荐 - 复数名词
GET /api/users
GET /api/orders
GET /api/products
# 不推荐 - 动词或混合约定
GET /api/getUser
GET /api/user (单复数不一致)
POST /api/createOrder
### 嵌套资源
# 浅层嵌套 (推荐)
GET /api/users/{id}/orders
GET /api/orders/{id}
# 深层嵌套 (避免)
GET /api/users/{id}/orders/{orderId}/items/{itemId}/reviews
# 更好:
GET /api/order-items/{id}/reviews
## HTTP 方法与状态码
### GET - 获取资源
GET /api/users → 200 OK (返回列表)
GET /api/users/{id} → 200 OK 或 404 Not Found
GET /api/users?page=2 → 200 OK (分页)
### POST - 创建资源
POST /api/users
Body: {"name": "John", "email": "
[email protected]"}
→ 201 Created
Location: /api/users/123
Body: {"id": "123", "name": "John", ...}
POST /api/users (验证错误)
→ 422 Unprocessable Entity
Body: {"errors": [...]}
### PUT - 替换资源
PUT /api/users/{id}
Body: {完整用户对象}
→ 200 OK (已更新)
→ 404 Not Found (不存在)
# 必须包含所有字段
### PATCH - 部分更新
PATCH /api/users/{id}
Body: {"name": "Jane"} (仅包含变更字段)
→ 200 OK
→ 404 Not Found
### DELETE - 删除资源
DELETE /api/users/{id}
→ 204 No Content (已删除)
→ 404 Not Found
→ 409 Conflict (因引用关系无法删除)
## 过滤、排序与搜索
### 查询参数
# 过滤
GET /api/users?status=active
GET /api/users?role=admin&status=active
# 排序
GET /api/users?sort=created_at
GET /api/users?sort=-created_at (降序)
GET /api/users?sort=name,created_at
# 搜索
GET /api/users?search=john
GET /api/users?q=john
# 字段选择 (稀疏字段集)
GET /api/users?fields=id,name,email
## 分页模式
### 基于偏移的分页
python
GET /api/users?page=2&page_size=20
响应:
{
"items": [...],
"page": 2,
"page_size": 20,
"total": 150,
"pages": 8
}
### 基于光标的分页 (适用于大数据集)
python
GET /api/users?limit=20&cursor=eyJpZCI6MTIzfQ
响应:
{
"items": [...],
"next_cursor": "eyJpZCI6MTQzfQ",
"has_more": true
}
### Link Header 分页 (RESTful)
GET /api/users?page=2
响应头:
Link: ; rel="next",
; rel="prev",
<https://api.exa