使用 JSON 的 REST API 是现代 Web 应用的基础。本指南将指导您构建可用于生产环境的 JSON API。
JSON REST 基础
REST(表述性状态转移)使用标准 HTTP 方法和 JSON 负载:
/api/users — 列出用户/api/users/1 — 获取单个用户/api/users — 创建用户/api/users/1 — 更新用户/api/users/1 — 删除用户请求和响应格式
创建用户的 POST 请求:
{
"firstName": "Jane",
"lastName": "Smith",
"email": "jane@example.com",
"role": "developer"
}
成功响应(201 Created):
{
"id": 42,
"firstName": "Jane",
"lastName": "Smith",
"email": "jane@example.com",
"role": "developer",
"createdAt": "2026-01-15T10:30:00Z"
}
过滤、排序和搜索
使用查询参数实现灵活的数据访问:
GET /api/users?role=developer&sort=-createdAt&limit=20
速率限制
在响应中包含速率限制头:
{
"data": [...],
"rateLimit": {
"remaining": 95,
"limit": 100,
"resetAt": "2026-01-15T11:00:00Z"
}
}
最佳实践总结
/users 而非 /user)/api/v1/)