RESTful API design patterns and best practices. Use when creating endpoints, designing APIs, or implementing routes.
本技能提供 RESTful API 开发的最佳实践和模式。
# 资源命名 - 使用名词复数
GET /api/v1/users # 获取用户列表
GET /api/v1/users/:id # 获取单个用户
POST /api/v1/users # 创建用户
PUT /api/v1/users/:id # 更新用户(完整替换)
PATCH /api/v1/users/:id # 更新用户(部分更新)
DELETE /api/v1/users/:id # 删除用户
# 嵌套资源
GET /api/v1/users/:id/orders # 用户的订单
GET /api/v1/users/:id/orders/:orderId # 用户的特定订单
# 动作资源
POST /api/v1/users/:id/activate # 激活用户
POST /api/v1/orders/:id/cancel # 取消订单
| 方法 | 语义 | 幂等 | 安全 |
|---|---|---|---|
| GET | 读取资源 | ✅ | ✅ |
| POST | 创建资源 | ❌ | ❌ |
| PUT | 完整更新 | ✅ | ❌ |
| PATCH | 部分更新 | ❌ | ❌ |
| DELETE | 删除资源 | ✅ | ❌ |
// 单个资源
{
"success": true,
"data": {
"id": "123",
"name": "张三",
"email": "zhangsan@example.com"
}
}
// 列表资源
{
"success": true,
"data": [
{ "id": "1", "name": "用户1" },
{ "id": "2", "name": "用户2" }
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 100,
"totalPages": 5
}
}
// 创建成功
{
"success": true,
"data": { "id": "123", ... },
"message": "创建成功"
}
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "请求参数无效",
"details": [
{ "field": "email", "message": "邮箱格式不正确" },
{ "field": "age", "message": "年龄必须大于 0" }
]
}
}
各框架的完整 CRUD 路由实现:
详见 Next.js API Patterns - App Router + Zod 验证 + 认证授权
详见 FastAPI Patterns - Pydantic 模型 + 异步路由
详见 Express.js Patterns - express-validator + 中间件
interface PaginationParams {
page?: number;
pageSize?: number;
cursor?: string; // 游标分页
}
// 偏移分页
const { page = 1, pageSize = 20 } = query;
const skip = (page - 1) * pageSize;
// 游标分页(大数据量推荐)
const { cursor, pageSize = 20 } = query;
const where = cursor ? { id: { gt: cursor } } : {};
// ?sort=createdAt:desc,name:asc
const sortParam = query.sort as string;
const orderBy = sortParam?.split(",").map((s) => {
const [field, order] = s.split(":");
return { [field]: order || "asc" };
}) || [{ createdAt: "desc" }];
// ?status=active&role=admin
const { status, role } = query;
const where = {
...(status && { status }),
...(role && { role }),
};
// ?q=keyword
const { q } = query;
const where = q
? {
OR: [
{ name: { contains: q, mode: "insensitive" } },
{ email: { contains: q, mode: "insensitive" } },
],
}
: {};
/api/v1/users
/api/v2/users
Accept: application/vnd.api+json; version=1
JWT 认证中间件和权限检查的完整实现详见 Next.js API Patterns
| 状态码 | 含义 | 使用场景 |
|---|---|---|
| 200 | OK | 成功获取/更新 |
| 201 | Created | 成功创建 |
| 204 | No Content | 成功删除 |
| 400 | Bad Request | 请求参数错误 |
| 401 | Unauthorized | 未认证 |
| 403 | Forbidden | 无权限 |
| 404 | Not Found | 资源不存在 |
| 409 | Conflict | 资源冲突 |
| 422 | Unprocessable Entity | 业务逻辑错误 |
| 429 | Too Many Requests | 请求过多 |
| 500 | Internal Server Error | 服务器错误 |
/users 而非 /user记住: API 设计的核心是一致性——统一的 URL 结构、响应格式、错误处理,让调用方可预测。