designing-apis
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDesigning APIs
API设计
When to Load
适用场景
- Trigger: Designing REST or GraphQL endpoints, API contracts, versioning, request/response formats
- Skip: Internal-only code with no API surface
- 触发场景:设计REST或GraphQL端点、API契约、版本控制、请求/响应格式
- 跳过场景:无API对外暴露的内部专属代码
API Design Workflow
API设计工作流
Copy this checklist and track progress:
API Design Progress:
- [ ] Step 1: Define resources and relationships
- [ ] Step 2: Design endpoint structure
- [ ] Step 3: Define request/response formats
- [ ] Step 4: Plan error handling
- [ ] Step 5: Add authentication/authorization
- [ ] Step 6: Document with OpenAPI spec
- [ ] Step 7: Validate design against checklist复制以下清单并跟踪进度:
API设计进度:
- [ ] 步骤1:定义资源及关联关系
- [ ] 步骤2:设计端点结构
- [ ] 步骤3:定义请求/响应格式
- [ ] 步骤4:规划错误处理
- [ ] 步骤5:添加认证/授权机制
- [ ] 步骤6:使用OpenAPI规范编写文档
- [ ] 步骤7:对照清单验证设计REST API Design
REST API设计
URL Structure
URL结构
undefinedundefinedResource-based URLs (nouns, not verbs)
基于资源的URL(使用名词,而非动词)
GET /users # List users
GET /users/:id # Get user
POST /users # Create user
PUT /users/:id # Replace user
PATCH /users/:id # Update user
DELETE /users/:id # Delete user
GET /users # 列出用户
GET /users/:id # 获取单个用户
POST /users # 创建用户
PUT /users/:id # 替换用户信息
PATCH /users/:id # 更新用户部分信息
DELETE /users/:id # 删除用户
Nested resources
嵌套资源
GET /users/:id/orders # User's orders
POST /users/:id/orders # Create order for user
GET /users/:id/orders # 获取用户的订单
POST /users/:id/orders # 为用户创建订单
Query parameters for filtering/pagination
用于筛选/分页的查询参数
GET /users?role=admin&status=active
GET /users?page=2&limit=20&sort=-createdAt
undefinedGET /users?role=admin&status=active
GET /users?page=2&limit=20&sort=-createdAt
undefinedHTTP Status Codes
HTTP状态码
| Code | Meaning | Use Case |
|---|---|---|
| 200 | OK | Successful GET, PUT, PATCH |
| 201 | Created | Successful POST |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Invalid input |
| 401 | Unauthorized | Missing/invalid auth |
| 403 | Forbidden | Valid auth, no permission |
| 404 | Not Found | Resource doesn't exist |
| 409 | Conflict | Duplicate, state conflict |
| 422 | Unprocessable | Validation failed |
| 429 | Too Many Requests | Rate limited |
| 500 | Internal Error | Server error |
| 状态码 | 含义 | 适用场景 |
|---|---|---|
| 200 | 请求成功 | 成功的GET、PUT、PATCH请求 |
| 201 | 已创建 | 成功的POST请求 |
| 204 | 无内容 | 成功的DELETE请求 |
| 400 | 错误请求 | 输入参数无效 |
| 401 | 未授权 | 缺少/无效的认证信息 |
| 403 | 禁止访问 | 认证有效但无权限 |
| 404 | 资源不存在 | 请求的资源不存在 |
| 409 | 冲突 | 重复请求或状态冲突 |
| 422 | 无法处理的请求 | 验证失败 |
| 429 | 请求过于频繁 | 触发速率限制 |
| 500 | 服务器内部错误 | 服务器端发生错误 |
Response Formats
响应格式
Success Response:
json
{
"data": {
"id": "123",
"type": "user",
"attributes": {
"name": "John Doe",
"email": "john@example.com"
}
},
"meta": {
"requestId": "abc-123"
}
}List Response with Pagination:
json
{
"data": [...],
"meta": {
"total": 100,
"page": 1,
"limit": 20,
"totalPages": 5
},
"links": {
"self": "/users?page=1",
"next": "/users?page=2",
"last": "/users?page=5"
}
}Error Response:
json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": [
{
"field": "email",
"message": "Must be a valid email address"
}
]
},
"meta": {
"requestId": "abc-123"
}
}成功响应:
json
{
"data": {
"id": "123",
"type": "user",
"attributes": {
"name": "John Doe",
"email": "john@example.com"
}
},
"meta": {
"requestId": "abc-123"
}
}带分页的列表响应:
json
{
"data": [...],
"meta": {
"total": 100,
"page": 1,
"limit": 20,
"totalPages": 5
},
"links": {
"self": "/users?page=1",
"next": "/users?page=2",
"last": "/users?page=5"
}
}错误响应:
json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": [
{
"field": "email",
"message": "Must be a valid email address"
}
]
},
"meta": {
"requestId": "abc-123"
}
}API Versioning
API版本控制
URL Versioning (Recommended):
/api/v1/users
/api/v2/usersHeader Versioning:
Accept: application/vnd.api+json; version=1URL版本控制(推荐):
/api/v1/users
/api/v2/users请求头版本控制:
Accept: application/vnd.api+json; version=1Authentication Patterns
认证模式
JWT Bearer Token:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...API Key:
X-API-Key: your-api-keyJWT Bearer令牌:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...API密钥:
X-API-Key: your-api-keyRate Limiting Headers
速率限制响应头
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1609459200
Retry-After: 60X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1609459200
Retry-After: 60GraphQL Patterns
GraphQL模式
Schema Design:
graphql
type Query {
user(id: ID!): User
users(filter: UserFilter, pagination: Pagination): UserConnection!
}
type Mutation {
createUser(input: CreateUserInput!): UserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UserPayload!
}
type User {
id: ID!
name: String!
email: String!
orders(first: Int, after: String): OrderConnection!
}
input CreateUserInput {
name: String!
email: String!
}
type UserPayload {
user: User
errors: [Error!]
}Schema设计:
graphql
type Query {
user(id: ID!): User
users(filter: UserFilter, pagination: Pagination): UserConnection!
}
type Mutation {
createUser(input: CreateUserInput!): UserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UserPayload!
}
type User {
id: ID!
name: String!
email: String!
orders(first: Int, after: String): OrderConnection!
}
input CreateUserInput {
name: String!
email: String!
}
type UserPayload {
user: User
errors: [Error!]
}OpenAPI Specification Template
OpenAPI规范模板
See OPENAPI-TEMPLATE.md for the full OpenAPI 3.0 specification template.
完整的OpenAPI 3.0规范模板请查看OPENAPI-TEMPLATE.md。
API Design Validation
API设计验证
After completing the design, validate against this checklist:
Validation Checklist:
- [ ] All endpoints use nouns, not verbs
- [ ] HTTP methods match operations correctly
- [ ] Consistent response format across endpoints
- [ ] Error responses include actionable details
- [ ] Pagination implemented for list endpoints
- [ ] Authentication defined for protected endpoints
- [ ] Rate limiting headers documented
- [ ] OpenAPI spec is complete and validIf validation fails, return to the relevant design step and address the issues.
完成设计后,对照以下清单进行验证:
验证清单:
- [ ] 所有端点使用名词而非动词
- [ ] HTTP方法与操作类型匹配正确
- [ ] 所有端点的响应格式保持一致
- [ ] 错误响应包含可操作的详细信息
- [ ] 列表端点已实现分页
- [ ] 受保护的端点已定义认证机制
- [ ] 速率限制响应头已文档化
- [ ] OpenAPI规范完整且有效如果验证不通过,请回到对应设计步骤解决问题。
Security Checklist
安全清单
- HTTPS only
- Authentication on all endpoints
- Authorization checks
- Input validation
- Rate limiting
- Request size limits
- CORS properly configured
- No sensitive data in URLs
- Audit logging
- 仅使用HTTPS
- 所有端点均需认证
- 已添加权限校验
- 已实现输入验证
- 已配置速率限制
- 已设置请求大小限制
- CORS配置正确
- URL中不包含敏感数据
- 已启用审计日志