Community编程与开发github.com

API与接口设计

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

API与接口设计 是什么?

此技能提供了一套全面的原则和模式,用于设计稳定、易于使用且难以误用的API与接口,涵盖REST API、GraphQL模式、模块边界和组件属性。其核心原则包括:契约先行(先定义接口后实现)、一致的错误语义、在系统边界进行验证、优先扩展而非修改、可预测的命名以及幂等性键的正确实现。该技能详细解释了Hyrum定律(任何可观察的行为都可能成为依赖)和单版本规则(避免依赖冲突),并提供了大量的TypeScript代码示例、REST API模式(如资源设计、分页、过滤和部分更新)和常见误区的澄清。对于任何构建公共或内部接口的开发者来说,该技能通过强调契约、安全演进和幂等性,帮助创建可维护且健壮的系统,减少生产环境中的破坏性变更和重复问题。

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

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

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

文档

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

概述

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

何时使用

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

核心原则

Hyrum定律

当API有足够多的用户时,系统的所有可观察行为都会被某些人依赖,无论你在契约中承诺了什么。

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

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

单版本规则

避免强制消费者在同一依赖或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 e;
}
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长时间运行的效果

绝不要让第二个调用方通过,因为第一个“似乎卡住了”。一个状态未知的停滞尝试正是重复成本最高的时候。

每次调用都有三种结果,而不是两种:成功、失败和未知。 超时告诉你关于效果是否已应用的任何信息。在调用外部之前记录意图,以便调用和响应之间的崩溃留下证据,证明某些事情必须在稍后解决——而不是静默重试的收费。

根据最长的重试链设置保留期,而不是磁盘成本。 键必须比所有能够重新传递相同意图的路径都长寿,包括一周后重放的死信队列和任何提供者争议窗口。在7天死信队列后面的24小时键TTL是一个等待发生的重复。

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

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进行版本控制”没有版本控制的破坏性更改会破坏消费者。从一开始就设计为可扩展。
“没人用那个未记录的行为”Hyrum定律:如果它是可观察的,就会有人依赖它。将每个公共行为视为一个承诺。
“我们可以维护两个版本”多个版本成倍增加维护成本并造成菱形依赖问题。优先使用单版本规则。
“内部API不需要契约”内部消费者仍然是消费者。契约防止耦合并支持并行工作。
“接受Idempotency-Key头就够了”头部是契约;针对结果存储键是实现。你接受但不履行的键告诉客户端重试是安全的,而事实并非如此。
“我们的队列保证精确一次传递”没有队列能在消费者崩溃的情况下做到这一点——代理的确认和你的副作用不在一个事务中。针对至少一次传递进行设计,并采用幂等处理。
“重复请求很少见”它们是相关的。重试正是在依赖降级时激增——正是重复最可能且成本最高的时候。

红旗标志

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

验证

设计API后:

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

Individual skills in this repo

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

alfathafp/portofolio-web-design

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.

alfathafp/portofolio-web-design

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.

alfathafp/portofolio-web-design

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. Use when asked to review a diff or a pull request, even when the diff is pasted inline.

alfathafp/portofolio-web-design

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.

alfathafp/portofolio-web-design

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.

alfathafp/portofolio-web-design

Optimizes agent context setup. Use when starting a new session, when agent output quality degrades, when switching between tasks, or when you need to configure rules files and context for a project.

alfathafp/portofolio-web-design

Guides systematic root-cause debugging. Use when tests fail, builds break, something that worked yesterday broke, behavior doesn't match expectations, or you encounter any unexpected error. Use when you need to figure out what broke and why — a systematic approach to finding and fixing the root cause rather than guessing.

alfathafp/portofolio-web-design

Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".

alfathafp/portofolio-web-design

Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.

alfathafp/portofolio-web-design

Use when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.

alfathafp/portofolio-web-design

Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies

alfathafp/portofolio-web-design

Records decisions and documentation. Use when you need to document an architecture decision (ADR) or the reasoning behind a design choice, when changing public APIs, shipping features, or when you need to record context that future engineers and agents will need to understand the codebase.

alfathafp/portofolio-web-design

Subjects every non-trivial decision to a fresh-context adversarial review before it stands. Use when you want every assumption cross-examined before proceeding, when stress-testing a plan for hidden failure modes, when correctness matters more than speed, when working in unfamiliar code, when stakes are high (production auth, security-sensitive logic, a high-stakes migration, irreversible operations), or any time a confident output would be cheaper to verify now than to debug later.

alfathafp/portofolio-web-design

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

alfathafp/portofolio-web-design

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work

alfathafp/portofolio-web-design

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.

alfathafp/portofolio-web-design

Structures git workflow practices. Use when making any code change. Use when committing, branching, resolving conflicts, splitting uncommitted work in a messy working tree into clean atomic commits, opening or reviewing a pull request (PR), pushing to a remote, or when you need to organize work across multiple parallel streams. Use when cutting a release, choosing a semantic version bump, tagging, or writing a changelog.

alfathafp/portofolio-web-design

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".

alfathafp/portofolio-web-design

Delivers changes incrementally in thin, verifiable slices. Use when implementing any feature or change that touches more than one file, or when picking up the next task from a plan. Use when rolling a change out behind a feature flag, 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.

alfathafp/portofolio-web-design

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).

相关技能