关于 api-design
面向 API 设计与开发者的设计指南和参考资料,覆盖 REST、GraphQL 与 gRPC。内容包含契约优先、版本管理、错误格式、分页和幂等性等实践,并附有规范与模板参考。
主要功能
- 01契约优先的 API 设计原则
- 02REST、GraphQL 与 gRPC 指南
- 03OpenAPI 3.2 文档建议
- 04错误处理与游标分页模式
- 05API 设计清单及模板
适用场景
- 01规划新 API 的接口契约
- 02为 REST API 设计版本和分页
- 03统一 GraphQL 或 gRPC 的错误处理
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ majiayu000/ spellbook --skill api-design安装后在 Claude Code 中输入/api-design确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
reference/comparison.mdgraphql.mdgrpc.mdrest.mdtemplates/graphql/schema.graphqltemplates/grpc/service.prototemplates/openapi/openapi.yaml详细介绍
API 设计
核心原则
- 契约优先 — 实现前先定义 API 规范
- OpenAPI 3.2 — 使用 OpenAPI 编写 REST API 文档
- URL 版本控制 — 在路径中指定版本
/v1/,并使用 Sunset 标头 - 幂等性 — PUT/DELETE 必须具备幂等性,POST 使用 Idempotency-Key
- 游标分页 — 避免基于偏移量的分页
- RFC 7807 错误 — 使用标准 Problem Details 格式
- 不保证向后兼容 — 删除,而非弃用
快速参考
何时使用何种方案
| 场景 | 选择 | 原因 |
|---|---|---|
| 公共 API / MVP | REST | 简单、通用、易于调试 |
| 前端驱动 / 移动端 | GraphQL | 按需获取数据 |
| 内部微服务 | gRPC | 高性能、强类型 |
| 实时数据 | gRPC / GraphQL Subscriptions | 双向流式传输 |
REST API 设计
资源命名
# Good
GET /users # List users
GET /users/123 # Get user
POST /users # Create user
PUT /users/123 # Replace user
PATCH /users/123 # Update user
DELETE /users/123 # Delete user
# Nested resources
GET /users/123/orders # User's orders
# Actions (when CRUD doesn't fit)
POST /users/123/activate # Action on resource
# Query parameters for filtering
GET /users?status=active&role=admin&limit=20
HTTP 方法
| 方法 | 用途 | 幂等 | 安全 |
|---|---|---|---|
| GET | 读取 | 是 | 是 |
| POST | 创建 | 否 | 否 |
| PUT | 替换 | 是 | 否 |
| PATCH | 更新 | 否 | 否 |
| DELETE | 删除 | 是 | 否 |
状态码
# Success
200 OK - Successful GET/PUT/PATCH
201 Created - Successful POST (include Location header)
204 No Content - Successful DELETE
# Client Errors
400 Bad Request - Malformed request syntax
401 Unauthorized - Missing/invalid authentication
403 Forbidden - Authenticated but not authorized
404 Not Found - Resource doesn't exist
409 Conflict - Duplicate/conflict (e.g., unique constraint)
422 Unprocessable - Validation failed
429 Too Many - Rate limited
# Server Errors
500 Internal Error - Unexpected server error
503 Unavailable - Service temporarily down
错误响应(RFC 7807)
{
"type": "https://api.example.com/errors/validation",
"title": "Validation Error",
"status": 422,
"detail": "The request contains invalid parameters",
"instance": "/users/123",
"errors": [
{ "field": "email", "message": "Invalid email format" },
{ "field": "age", "message": "Must be positive integer" }
]
}
分页(基于游标)
// Request
GET /users?limit=20&cursor=eyJpZCI6MTAwfQ
// Response
{
"data": [...],
"pagination": {
"next_cursor": "eyJpZCI6MTIwfQ",
"prev_cursor": "eyJpZCI6ODB9",
"has_next": true,
"has_prev": true,
"limit": 20
}
}
版本控制
# URL versioning (recommended)
GET /v1/users
GET /v2/users
# Deprecation headers
Sunset: Sat, 31 Dec 2025 23:59:59 GMT
Deprecation: true
Link: </v2/users>; rel="successor-version"
幂等性
# For non-idempotent operations (POST)
POST /orders
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
# Server stores result and returns same response for duplicate key
GraphQL 设计
Schema 原则
- 领域驱动 — Schema 应反映业务领域,而非数据库
- 描述性命名 — 使用清晰的字段和类型名称,便于监控
- 限制嵌套 — 深层嵌套会影响性能
- 使用 @key — 标记用于 Federation 的实体标识符
类型定义
type Query {
user(id: ID!): User
users(first: Int, after: String, filter: UserFilter): UserConnection!
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}
type User @key(fields: "id") {
id: ID!
email: String!
name: String!
orders(first: Int, after: String): OrderConnection!
createdAt: DateTime!
}
# Relay-style pagination
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
错误处理
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}
# Union for typed errors
union CreateUserPayload = User | ValidationError | ConflictError
type ValidationError {
message: String!
field: String
code: String!
}
type ConflictError {
message: String!
existingId: ID!
}
防止 N+1 问题
// Use DataLoader for batching
const userLoader = new DataLoader(async (ids: string[]) => {
const users = await db.user.findMany({
where: { id: { in: ids } }
});
return ids.map(id => users.find(u => u.id === id));
});
// Resolver
const resolvers = {
Order: {
user: (order) => userLoader.load(order.userId),
},
};
gRPC 设计
Proto 定义
syntax = "proto3";
package api.v1;
import "google/protobuf/timestamp.proto";
import "google/protobuf/empty.proto";
service UserService {
// Unary
rpc GetUser(GetUserRequest) returns (User);
rpc CreateUser(CreateUserRequest) returns (User);
// Server streaming
rpc ListUsers(ListUsersRequest) returns (stream User);
// Client streaming
rpc BatchCreateUsers(stream CreateUserRequest) returns (BatchCreateResponse);
// Bidirectional streaming
rpc SyncUsers(stream UserUpdate) returns (stream UserUpdate);
}
message User {
string id = 1;
string email = 2;
string name = 3;
google.protobuf.Timestamp created_at = 4;
}
message GetUserRequest {
string id = 1;
}
message ListUsersRequest {
int32 page_size = 1;
string page_token = 2;
UserFilter filter = 3;
}
message UserFilter {
optional string status = 1;
optional string role = 2;
}
错误处理
// Use Google's richer error model
import "google/rpc/status.proto";
import "google/rpc/error_details.proto";
// For streaming: embed errors in response
message StreamResponse {
oneof result {
User user = 1;
StreamError error = 2;
}
}
message StreamError {
string code = 1;
string message = 2;
map<string, string> details = 3;
}
截止时间与重试
// Always set deadlines
const deadline = new Date();
deadline.setSeconds(deadline.getSeconds() + 5);
const user = await client.getUser(
{ id: '123' },
{ deadline }
);
// Configure retry policy
const retryPolicy = {
maxAttempts: 3,
initialBackoff: '0.1s',
maxBackoff: '1s',
backoffMultiplier: 2,
retryableStatusCodes: ['UNAVAILABLE', 'DEADLINE_EXCEEDED'],
};
速率限制
标头
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200
Retry-After: 60
响应(429)
{
"type": "https://api.example.com/errors/rate-limited",
"title": "Rate Limit Exceeded",
"status": 429,
"detail": "You have exceeded the rate limit of 100 requests per minute",
"retryAfter": 60
}
检查清单
## Design
- [ ] API spec defined before implementation
- [ ] Resources use plural nouns
- [ ] Correct HTTP methods/status codes
- [ ] RFC 7807 error format
## Features
- [ ] Cursor-based pagination
- [ ] Rate limiting with headers
- [ ] Idempotency keys for POST
- [ ] API versioning strategy
## Documentation
- [ ] OpenAPI/GraphQL schema published
- [ ] Examples for all endpoints
- [ ] Error codes documented
## Operations
- [ ] Request/response logging
- [ ] Latency and error rate metrics
- [ ] Deprecation notices for old versions
另请参阅
- reference/rest.md — REST 深入介绍
- reference/graphql.md — GraphQL 模式
- reference/grpc.md — gRPC 模式
- reference/comparison.md — 选择指南
- templates/openapi/openapi.yaml — OpenAPI 入门契约
- templates/graphql/schema.graphql — GraphQL Schema 入门模板
- templates/grpc/service.proto — gRPC 服务入门模板
评论
支持 Markdown