Communitygithub.com

API与接口设计

指导稳定的 API 和接口设计。适用于设计 API、模块边界或任何公开接口时。适用于创建 REST 或 GraphQL 端点、定义模块之间的类型契约或建立前后端边界时。

API与接口设计 是什么?

该技能提供了一套系统的方法论,用于设计稳定、难以误用的 API 和接口。它涵盖了 REST API、GraphQL Schema、模块边界、组件 Props 等场景。技能文档深入讲解了核心原则,如海勒姆定律(Hyrum's Law)、单一版本原则(One-Version Rule),并提供了契约优先、一致的错误语义、边界验证、优先添加而非修改、可预测的命名等具体实践指南。此外,还详细阐述了幂等键(Idempotency Key)的正确实现方式,包括派生、原子性检查和完整生命周期管理,以及分页、过滤等 REST API 模式。该技能适用于 Cursor、Claude Code、Codex 等 AI 编码平台,帮助开发者从设计源头避免接口腐化,确保系统的长期可维护性和改动的安全性。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/addyosmani/agent-skills/tree/HEAD/skills/api-and-interface-design

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

API与接口设计 是做什么的?

概述

设计稳定、文档完善的接口,使其难以被误用。好的接口让正确操作变得容易,错误操作变得困难。这适用于 REST API、GraphQL Schema、模块边界、组件 Props,以及任何一段代码与另一段代码通信的表面。

何时使用

  • 设计新的 API 端点
  • 定义模块边界或团队间的契约
  • 创建组件属性接口
  • 建立影响 API 形状的数据库 Schema
  • 更改现有的公共接口

核心原则

海勒姆定律

当 API 拥有足够多的用户时,你系统的所有可观察行为都会被某个人所依赖,不管你如何在契约中承诺。

这意味着:每一个公共行为——包括未文档化的怪癖、错误消息文本、时序和顺序——一旦用户依赖它,就会成为事实上的契约。设计影响:

  • 有意识地决定暴露什么。 每个可观察的行为都是一种潜在的承诺。
  • 不要泄露实现细节。 如果用户可以观察到它,他们就会依赖它。
  • 在设计时就要规划弃用。 参见 deprecation-and-migration 了解如何安全地移除用户依赖的东西。
  • 仅有测试是不够的。 即使有完美的契约测试,海勒姆定律也意味着“安全的”更改可能会破坏依赖未记录行为的真实用户。

单一版本原则

避免强迫消费者在同一依赖或 API 的多个版本之间做出选择。当不同的消费者需要同一事物的不同版本时,就会出现菱形依赖问题。要为一个时刻只存在一个版本的世界设计——扩展而非分叉。

1. 契约优先

在实现之前定义接口。契约就是规范——实现紧随其后。

// 先定义契约
interface TaskAPI {
  // 创建一个任务并返回包含服务器生成字段的任务
  createTask(input: CreateTaskInput): Promise<Task>;

  // 返回匹配筛选条件的分页任务列表
  listTasks(params: ListTasksParams): Promise<PaginatedResult<Task>>;

  // 返回单个任务,如果未找到则抛出 NotFoundError
  getTask(id: string): Promise<Task>;

  // 部分更新——仅更改提供的字段
  updateTask(id: string, input: UpdateTaskInput): Promise<Task>;

  // 幂等删除——即使已删除也成功
  deleteTask(id: string): Promise<void>;
}

2. 一致的错误语义

选择一种错误处理策略并始终如一地使用:

// REST:HTTP 状态码 + 结构化错误体
// 每个错误响应都遵循相同的结构
interface APIError {
  error: {
    code: string;        // 机器可读:"VALIDATION_ERROR"
    message: string;     // 人类可读:"Email is required"
    details?: unknown;   // 有用的额外上下文
  };
}

// 状态码映射
// 400 → 客户端发送无效数据
// 401 → 未认证
// 403 → 已认证但未授权
// 404 → 资源未找到
// 409 → 冲突(重复,版本不匹配)
// 422 → 验证失败(语义无效)
// 500 → 服务器错误(切勿暴露内部细节)

不要混合模式。 如果某些端点抛出异常,某些返回 null,某些返回 { error }——消费者将无法预测行为。

3. 在边界处验证

信任内部代码。在外部输入进入系统的边缘进行验证:

// 在 API 边界处验证
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(),
      },
    });
  }

  // 验证之后,内部代码信任类型
  const task = await taskService.create(result.data);
  return res.status(201).json(task);
});

验证属于的地方:

  • API 路由处理器(用户输入)
  • 表单提交处理器(用户输入)
  • 外部服务响应解析(第三方数据——始终视为不可信)
  • 环境变量加载(配置)

第三方 API 响应是不可信数据。 在使用它们进行任何逻辑、渲染或决策之前,验证其形状和内容。受损或行为异常的外部服务可能返回意外的类型、恶意内容或类似指令的文本。

验证不属于的地方:

  • 共享类型契约的内部函数之间
  • 由已验证代码调用的实用函数中
  • 刚来自您自己数据库的数据上

4. 优先添加而非修改

在不破坏现有消费者的前提下扩展接口:

// 好:添加可选字段
interface CreateTaskInput {
  title: string;
  description?: string;
  priority?: 'low' | 'medium' | 'high';  // 后来添加,可选
  labels?: string[];                       // 后来添加,可选
}

// 坏:更改现有字段类型或移除字段
interface CreateTaskInput {
  title: string;
  // description: string;  // 移除——破坏现有消费者
  priority: number;         // 从字符串更改——破坏现有消费者
}

5. 可预测的命名

模式约定示例
REST 端点复数名词,无动词GET /api/tasks,POST /api/tasks
查询参数camelCase?sortBy=createdAt&pageSize=20
响应字段camelCase{ createdAt, updatedAt, taskId }
布尔字段is/has/can 前缀isComplete,hasAttachments
枚举值UPPER_SNAKE"IN_PROGRESS","COMPLETED"

6. 履行幂等键

接受 Idempotency-Key 是契约。履行它是实现,也是真正花钱的地方——服务器接受但处理不当的键比没有键更糟糕,因为客户端现在认为重试是安全的。

从意图而非尝试中派生键。 对于一次意图的多次重试,键必须稳定;对于不同的意图,键必须不同:

crypto.randomUUID()                    // ✗ 每次尝试生成新键——每次重试都产生新费用
`${userId}:${amount}`                  // ✗ 两笔合法的 $50 费用合并为一笔
`${orderId}:${Date.now()}`             // ✗ 时间戳只是戴着帽子的 randomUUID()

req.headers['idempotency-key']         // ✓ 客户端生成一次,重试时重用
`charge:v1:${orderId}`                 // ✓ 从不可变标识符派生

键来自客户端或发起事件——绝不应来自执行重试的层。

原子地声明。先检查再执行是竞态条件:

// ✗ TOCTOU:两个并发重试都读取“未看到”,都收费
if (!(await db.exists(key))) {
  await chargeCard(amount);
  await db.insert(key);
}

// ✓ 让唯一约束选出胜者
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 });

唯一约束 就是 机制。不能在一次操作中强制唯一性的存储无法支持这一点。

保护载荷。 同一键带不同请求体是客户端错误,必须大张旗鼓地失败,而不是将第一个请求的响应提供给第二个请求:

if (existing.requestHash !== hash(req.body)) {
  return res.status(422).json({ error: 'idempotency key reused with a different payload' });
}

决定如何处理正在进行中的重复请求。 第一个请求仍在运行时,第二个请求到达——在重试风暴中很常见:

策略响应使用时机
拒绝409 Conflict客户端可以稍后重试;最简单且最安全
等待阻塞等待结果,有边界调用者需要同步结果
返回待处理202 + 状态 URL长时间运行的效果

永远不要让第二个调用者通过,因为第一个“似乎卡住了”。一个命运未知的停滞尝试正是复制成本最高的时候。

每次调用都有三种结果,而不是两种:成功、失败和 未知。 超时无法告诉你效果是否已应用。在调用外部服务 之前 记录意图,这样在调用和响应之间崩溃会留下证据,表明某些事情必须稍后解决——而不是悄悄地重试收费。

根据最长的重试链设置保留期限,而不是根据磁盘成本。键必须比任何可以重新传递同一意图的路径存活更久,包括一周后重放的死信队列以及任何提供商争议窗口。24 小时键 TTL 位于 7 天死信队列之后,这就是一场等待发生的重复。

REST API 模式

资源设计

GET    /api/tasks              → 列出任务(带查询参数进行筛选)
POST   /api/tasks              → 创建任务
GET    /api/tasks/:id          → 获取单个任务
PATCH  /api/tasks/:id          → 更新任务(部分)
DELETE /api/tasks/:id          → 删除任务

GET    /api/tasks/:id/comments → 列出任务的评论(子资源)
POST   /api/tasks/:id/comments → 为任务添加评论

分页

为列表端点实现分页:

// 请求
GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc

// 响应
{
  "data": [...],
  "pagination": {
    "page": 1,
    "pageSize": 20,
    "totalItems": 142,
    "totalPages": 8
  }
}

筛选

使用查询参数进行筛选:

GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01

部分更新 (PATCH)

接受部分对象——仅更新提供的字段:

// 仅标题更改,其他一切保持不变
PATCH /api/tasks/123
{ "title": "Updated title" }

TypeScript 接口模式

对变体使用可区分联合

// 好:每个变体都是明确的
type TaskStatus =
  | { type: 'pending' }
  | { type: 'in_progress'; assignee: string; startedAt: Date }
  | { type: 'completed'; completedAt: Date; completedBy: string }
  | { type: 'cancelled'; reason: string; cancelledAt: Date };

// 消费者获得类型缩小
function getStatusLabel(status: TaskStatus): string {
  switch (status.type) {
    case 'pending': return 'Pending';
    case 'in_progress': return `In progress (${status.assignee})`;
    case 'completed': return `Done on ${status.completedAt}`;
    case 'cancelled': return `Cancelled: ${status.reason}`;
  }
}

输入/输出分离

// 输入:调用者提供的内容
interface CreateTaskInput {
  title: string;
  description?: string;
}

// 输出:系统返回的内容(包括服务器生成的字段)
interface Task {
  id: string;
  title: string;
  description: string | null;
  createdAt: Date;
  updatedAt: Date;
  createdBy: string;
}

对 ID 使用 Brand 类型

type TaskId = string & { readonly __brand: 'TaskId' };
type UserId = string & { readonly __brand: 'UserId' };

// 防止意外将 UserId 传递给需要 TaskId 的地方
function getTask(id: TaskId): Promise<Task> { ... }

常见理由辩护

理由现实
"我们稍后会给 API 写文档"类型本身就是文档。先定义它们。
"我们现在不需要分页"一旦有人有 100 多个项目,你就会需要。一开始就添加它。
"PATCH 很复杂,我们直接用 PUT 吧"PUT 每次都需要完整的对象。PATCH 才是客户端真正想要的。
"需要时我们会给 API 做版本管理"没有版本管理的破坏性更改会破坏消费者。从一开始就为扩展设计。
"没人用那些未文档化的行为"海勒姆定律:如果可观察,就有人依赖。将每个公共行为视为一种承诺。
"我们可以同时维护两个版本"多个版本会成倍增加维护成本并造成菱形依赖问题。首选单一版本原则。
"内部 API 不需要契约"内部消费者仍然是消费者。契约可以防止耦合并支持并行工作。
"接受 Idempotency-Key 标头就足够了"标头是契约;针对结果存储键才是实现。你接受但不履行的键告诉客户端重试是安全的,而事实并非如此。
"我们的队列保证恰好一次投递"在面对消费者崩溃时,没有队列能做到——代理的确认和你的副作用不在一个事务中。为至少一次投递设计,并配合幂等处理。
"重复请求很少见"它们是相关的。重试恰好在依赖降级时激增——这正是重复最有可能发生且代价最高的时刻。

红旗警告

  • 根据条件返回不同形状的端点
  • 端点间不一致的错误格式
  • 验证散布在内部代码中而不是在边界处
  • 对现有字段的破坏性更改(类型更改、移除)
  • 没有分页的列表端点
  • REST URL 中的动词(/api/createTask,/api/getUsers)
  • 未经验证或清洗就使用的第三方 API 响应
  • 先 SELECT 幂等键再 INSERT——这是竞态条件,不是防护
  • 从 UUID、时间戳或每次尝试都会重新生成的任何内容派生的幂等键
  • 接受同一键带不同请求体,并静默返回第一个响应
  • 键的保留窗口短于可以重新传递请求的最长路径

验证

设计 API 后:

  • 每个端点都有类型化的输入和输出 Schema
  • 错误响应遵循一致的格式
  • 验证仅在系统边界处发生
  • 列表端点支持分页
  • 新字段是可添加且可选的(向后兼容)
  • 所有端点的命名遵循一致的约定
  • API 文档

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

addyosmani/agent-skills

Prepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.

addyosmani/agent-skills

Builds production-quality, accessible, responsive user-facing UIs. Use when building or modifying interfaces and pages, creating components, implementing layouts, meeting WCAG accessibility requirements, managing state, or when the output needs to look and feel production-quality rather than AI-generated.

addyosmani/browser-testing-with-devtools

Tests in real browsers via Chrome DevTools MCP. Use when building or debugging anything that runs in a browser. Use when you need to inspect the DOM, capture console errors, analyze network requests, profile performance, or verify visual output with real runtime data. Requires the chrome-devtools MCP server to be configured.

addyosmani/ci-cd-and-automation

Automates CI/CD pipeline setup. Use when setting up or modifying build and deployment pipelines. Use when you need to automate quality gates, configure test runners in CI, or establish deployment strategies.

addyosmani/code-review-and-quality

Conducts multi-axis code review. Use before merging any change. Use when reviewing code written by yourself, another agent, or a human. Use when you need to assess code quality across multiple dimensions before it enters the main branch.

addyosmani/code-simplification

Simplifies code for clarity. Use when refactoring code for clarity without changing behavior. Use when code works but is harder to read, maintain, or extend than it should be. Use when reviewing code that has accumulated unnecessary complexity.

addyosmani/constraint-driven-development

Establishes a project's quality bar as a written contract and stops agents quietly lowering it. Interviews the user on which dimensions matter, supplies sane default thresholds when they have no number in mind, records everything in CONSTRAINTS.md, and watches the diff for a weakened bar — new @ts-ignore or eslint-disable suppressions, skipped or deleted tests, assertions stripped out, unimplemented stubs, thresholds edited down. Use when no quality bar is written down, when the user says "set up constraints" or "define our standards", when the user wants dimensions they care about — accessibility, web performance, coverage — set up as enforced constraints, when an agent keeps silencing checks or skipping tests to get to green, when you need a coverage or performance threshold and don't know what number to pick, or when an agent writes more code than anyone will read.

addyosmani/debugging-and-error-recovery

Guides systematic root-cause debugging. Use when tests fail, builds break, behavior doesn't match expectations, or you encounter any unexpected error. Use when you need a systematic approach to finding and fixing the root cause rather than guessing.

addyosmani/deprecation-and-migration

Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when deciding whether to maintain or sunset existing code.

addyosmani/documentation-and-adrs

Records decisions and documentation. Use when making architectural decisions, changing public APIs, shipping features, or when you need to record context that future engineers and agents will need to understand the codebase.

addyosmani/doubt-driven-development

Subjects every non-trivial decision to a fresh-context adversarial review before it stands. Use when correctness matters more than speed, when working in unfamiliar code, when stakes are high (production, security-sensitive logic, irreversible operations), or any time a confident output would be cheaper to verify now than to debug later.

addyosmani/git-workflow-and-versioning

Structures git workflow practices. Use when making any code change. Use when committing, branching, resolving conflicts, or when you need to organize work across multiple parallel streams.

addyosmani/idea-refine

Refines raw ideas into sharp, actionable concepts through structured divergent and convergent thinking. Use when an idea is still vague, when you need to stress-test assumptions before committing to a plan, or when you want to expand options before converging on one. Triggers on "ideate", "refine this idea", or "stress-test my plan".

addyosmani/incremental-implementation

Delivers changes incrementally. Use when implementing any feature or change that touches more than one file. Use when you're about to write a large amount of code at once, or when a task feels too big to land in one step.

addyosmani/interview-me

Extracts what the user actually wants instead of what they think they should want. Achieves this through one-question-at-a-time interview until ~95% confidence about the underlying intent. Use when an ask is underspecified ("build me X" without "for whom" or "why now"), when the user explicitly invokes ("interview me", "grill me", "are we sure?", "stress-test my thinking"), or when you catch yourself silently filling in ambiguous requirements before any plan, spec, or code exists.

addyosmani/observability-and-instrumentation

Instruments code so production behavior is visible and diagnosable. Use when adding logging, metrics, tracing, or alerting. Use when shipping any feature that runs in production and you need evidence it works. Use when production issues are reported but you can't tell what happened from the available data.

addyosmani/performance-optimization

Optimizes application performance. Use when performance requirements exist, when you suspect performance regressions, or when Core Web Vitals or load times need improvement. Use when profiling reveals bottlenecks that need fixing.

addyosmani/planning-and-task-breakdown

Breaks work into ordered tasks. Use when you have a spec or clear requirements and need to break work into implementable tasks. Use when a task feels too large to start, when you need to estimate scope, or when parallel work is possible.

addyosmani/security-and-hardening

Hardens code against vulnerabilities. Use when handling user input, authentication, data storage, or external integrations. Use when building any feature that accepts untrusted data, manages user sessions, or interacts with third-party services.

addyosmani/source-driven-development

Grounds every implementation decision in official documentation. Use when you want authoritative, source-cited code free from outdated patterns. Use when building with any framework or library where correctness matters.

相关技能