api-and-interface-design
指导稳定的 API 和接口设计。设计 API、模块边界或任何公共接口时使用。创建 REST 或 GraphQL endpoint、定义模块之间的类型契约,或建立前后端边界时使用。
vinvcn · Static checks on file
Installation
Read the source and dependencies before running a command. Copying does not install or execute anything.
npx skills add vinvcn/addyosmani-agent-skills-zh --skill api-and-interface-designAbout this skill
name: api-and-interface-design description: 指导稳定的 API 和接口设计。设计 API、模块边界或任何公共接口时使用。创建 REST 或 GraphQL endpoint、定义模块之间的类型契约,或建立前后端边界时使用。
API 与接口设计
概览
设计稳定、文档清晰且难以误用的接口。好的接口让正确的事情容易做,让错误的事情难做。这适用于 REST API、GraphQL schema、模块边界、组件 props,以及任何一段代码与另一段代码对话的表面。
何时使用
- 设计新的 API endpoint
- 定义模块边界或团队之间的契约
- 创建组件 prop 接口
- 建立会影响 API 形态的数据库 schema
- 修改现有公共接口
核心原则
Hyrum's Law
只要 API 用户足够多,系统中所有可观察行为都会被某些人依赖,无论你在契约中承诺了什么。
这意味着:每个公共行为,包括未记录的怪癖、错误消息文本、时序和排序,一旦被用户依赖,就会成为事实契约。设计含义:
- 有意识地决定暴露什么。 每个可观察行为都是潜在承诺。
- 不要泄漏实现细节。 如果用户能观察到,他们就会依赖它。
- 在设计时规划废弃。 如何安全移除用户依赖的内容,见
deprecation-and-migration。 - 测试还不够。 即使有完美的契约测试,Hyrum's Law 也意味着“安全”的改动仍会破坏依赖未记录行为的真实用户。
单版本规则
避免迫使消费者在同一个依赖或 API 的多个版本之间选择。当不同消费者需要同一事物的不同版本时,就会出现 diamond dependency 问题。为一次只存在一个版本的世界设计:扩展,而不是 fork。
1. 契约优先
先定义接口,再实现它。契约就是规格,实现随后而来。
// Define the contract first
interface TaskAPI {
// Creates a task and returns the created task with server-generated fields
createTask(input: CreateTaskInput): Promise<Task>;
// Returns paginated tasks matching filters
listTasks(params: ListTasksParams): Promise<PaginatedResult<Task>>;
// Returns a single task or throws NotFoundError
getTask(id: string): Promise<Task>;
// Partial update — only provided fields change
updateTask(id: string, input: UpdateTaskInput): Promise<Task>;
// Idempotent delete — succeeds even if already deleted
deleteTask(id: string): Promise<void>;
}
2. 一致的错误语义
选择一种错误策略,并在所有地方使用它:
// REST: HTTP status codes + structured error body
// Every error response follows the same shape
interface APIError {
error: {
code: string; // Machine-readable: "VALIDATION_ERROR"
message: string; // Human-readable: "Email is required"
details?: unknown; // Additional context when helpful
};
}
// Status code mapping
// 400 → Client sent invalid data
// 401 → Not authenticated
// 403 → Authenticated but not authorized
// 404 → Resource not found
// 409 → Conflict (duplicate, version mismatch)
// 422 → Validation failed (semantically invalid)
// 500 → Server error (never expose internal details)
不要混用模式。 如果有些 endpoint throw,有些返回 null,有些返回 { error },消费者就无法预测行为。
3. 在边界验证
信任内部代码。在外部输入进入系统的边缘进行验证:
// Validate at the API boundary
app.post('/api/tasks', async (req, res) => {
const result = CreateTaskSchema.safeParse(req.body);
if (!result.success) {
return res.status(422).json({
error: {
code: 'VALIDATION_ERROR',
message: 'Invalid task data',
details: result.error.flatten(),
},
});
}
// After validation, internal code trusts the types
const task = await taskService.create(result.data);
return res.status(201).json(task);
});
验证应该放在:
- API route handlers(用户输入)
- Form submission handlers(用户输入)
- 外部服务响应解析(第三方数据 -- 始终视为不可信)
- 环境变量加载(配置)
第三方 API 响应是不可信数据。 在任何逻辑、渲染或决策中使用前,先验证其形态和内容。被攻陷或异常的外部服务可能返回意外类型、恶意内容或类似指令的文本。
验证不应该放在:
- 共享类型契约的内部函数之间
- 被已验证代码调用的 utility functions 中
- 刚从你自己的数据库中取出的数据上
4. 优先添加,而不是修改
扩展接口时不要破坏现有消费者:
// Good: Add optional fields
interface CreateTaskInput {
title: string;
description?: string;
priority?: 'low' | 'medium' | 'high'; // Added later, optional
labels?: string[]; // Added later, optional
}
// Bad: Change existing field types or remove fields
interface CreateTaskInput {
title: string;
// description: string; // Removed — breaks existing consumers
priority: number; // Changed from string — breaks existing consumers
}
5. 可预测命名
| 模式 | 约定 | 示例 |
|---|---|---|
| REST endpoints | 复数名词,不用动词 | GET /api/tasks, POST /api/tasks |
| Query params | camelCase | ?sortBy=createdAt&pageSize=20 |
| Response fields | camelCase | { createdAt, updatedAt, taskId } |
| Boolean fields | is/has/can 前缀 | isComplete, hasAttachments |
| Enum values | UPPER_SNAKE | "IN_PROGRESS", "COMPLETED" |
6. 兑现 Idempotency Key
接受 Idempotency-Key 是契约,兑现它才是实现,钱也正是从这里亏掉的。服务器接受了 key 却处理得漫不经心,比完全没有 key 更糟,因为客户端从此以为重试是安全的。
从意图派生 key,而不是从单次尝试。 同一个意图的多次重试之间 key 必须保持稳定,不同意图之间必须不同:
crypto.randomUUID() // ✗ new key per attempt — every retry is a new charge
`${userId}:${amount}` // ✗ two legitimate $50 charges collapse into one
`${orderId}:${Date.now()}` // ✗ a timestamp is randomUUID() wearing a hat
req.headers['idempotency-key'] // ✓ client generates once, reuses on retry
`charge:v1:${orderId}` // ✓ derived from an immutable identifier
key 来自客户端或发起事件,绝不来自负责重试的那一层。
原子地认领。先检查再执行就是一场 race:
// ✗ TOCTOU: two concurrent retries both read "not seen", both charge
if (!(await db.exists(key))) {
await chargeCard(amount);
await db.insert(key);
}
// ✓ let the unique constraint pick the winner
try {
await db.insert({ key, state: 'in_progress', requestHash });
} catch (e) {
if (isUniqueViolation(e)) return replayOrReject(key);
throw;
}
const result = await chargeCard(amount);
await db.update({ key, state: 'succeeded', response: result });
unique constraint 就是这个机制。无法在单个操作中强制唯一性的存储,支撑不了这套设计。
守住 payload。 同一个 key 配上不同的 body 是客户端 bug,必须大声报错失败,而不是把第一次的响应直接发给第二个请求:
if (existing.requestHash !== hash(req.body)) {
return res.status(422).json({ error: 'idempotency key reused with a different payload' });
}
想清楚 in-flight 的重复请求会得到什么。 第二个请求到达时第一个还在执行,这在 retry storm 下是常态:
| 策略 | 响应 | 适用场景 |
|---|---|---|
| 拒绝 | 409 Conflict | 客户端稍后可以重试;最简单也最安全 |
| 等待 | 阻塞等待结果,设置上限 | 调用方需要同步拿到结果 |
| 返回 pending | 202 + status URL | 长时间运行的副作用 |
绝不能因为第一个请求“看起来卡住了”就放行第二个调用方。一次停滞的尝试、结果未知,恰恰是重复执行代价最高的时刻。
每次调用有三种结果,不是两种:成功、失败,以及 未知。 超时说明不了副作用是否已经生效。在发起调用之前先记录意图,这样如果崩溃发生在调用与响应之间,会留下“有事情待解决”的证据,而不是让一笔扣款被悄悄重试。
保留期取决于最长的 retry chain,而不是磁盘成本。key 必须比所有可能重新投递同一意图的路径活得更久,包括一周后重放的 dead-letter queue 和任何 provider 的 dispute 窗口。7 天的 DLQ 后面配 24 小时的 key TTL,重
Read the complete source ↗