api-and-interface-design
它能做什么
这份指南帮助你设计易于使用、不容易被误用的接口(比如 API,或程序各部分之间的“约定”)。它教你如何清晰、稳定地定义不同软件部分之间的通信方式。
适用场景
- ✓当你要创建程序之间的新连接(API)时。
- ✓当你要定义同一个程序的不同部分如何通信时。
- ✓当你要规划程序与用户的交互方式(图形界面)时。
技能链接
https://github.com/addyosmani/agent-skills/blob/main/skills/api-and-interface-design/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“帮我定义一下,用户如何在系统中创建一个新任务,并指定标题和描述。”
每周 5 个新技能,1 分钟读完。
工作原理
它的做法是先确定通信方式(即“约定”),再开始编写代码。这样可以确保每个人都理解规则,避免意外情况。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
API and Interface Design
Overview
Design stable, well-documented interfaces that are hard to misuse. Good interfaces make the right thing easy and the wrong thing hard. This applies to REST APIs, GraphQL schemas, module boundaries, component props, and any surface where one piece of code talks to another.
When to Use
- Designing new API endpoints
- Defining module boundaries or contracts between teams
- Creating component prop interfaces
- Establishing database schema that informs API shape
- Changing existing public interfaces
Core Principles
Hyrum's Law
With a sufficient number of users of an API, all observable behaviors of your system will be depended on by somebody, regardless of what you promise in the contract.
This means: every public behavior — including undocumented quirks, error message text, timing, and ordering — becomes a de facto contract once users depend on it. Design implications:
- Be intentional about what you expose. Every observable behavior is a potential commitment.
- Don't leak implementation details. If users can observe it, they will depend on it.
- Plan for deprecation at design time. See
deprecation-and-migrationfor how to safely remove things users depend on. - Tests are not enough. Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior.
The One-Version Rule
Avoid forcing consumers to choose between multiple versions of the same dependency or API. Diamond dependency problems arise when different consumers need different versions of the same thing. Design for a world where only one version exists at a time — extend rather than fork.
1. Contract First
Define the interface before implementing it. The contract is the spec — implementation follows.
// 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. Consistent Error Semantics
Pick one error strategy and use it everywhere:
// 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)
Don't mix patterns. If some endpoints throw, others return null, and others return { error } — the consumer can't predict behavior.
3. Validate at Boundaries
Trust internal code. Validate at system edges where external input enters:
// 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);
});
Where validation belongs:
- API route handlers (user input)
- Form submission handlers (user input)
- External service response parsing (third-party data -- always treat as untrusted)
- Environment variable loading (configuration)
Third-party API responses are untrusted data. Validate their shape and content before using them in any logic, rendering, or decision-making. A compromised or misbehaving external service can return unexpected types, malicious content, or instruction-like text.
Where validation does NOT belong:
…
常见问题
什么是 API?
API 就像一份餐厅菜单:它规定了你可以点什么(功能)以及怎么点(参数),而你无需知道厨房(程序)是如何做菜的。
为什么“先定约定”很重要?
这就像开始游戏前先约定好规则。如果大家都清楚规则(即约定),游戏(程序)就会进行得更顺畅,也更不容易产生冲突。
什么是“海勒姆定律”(Hyrum's Law)?
它的意思是:如果很多人使用某个东西,他们最终会依赖它的所有细节,包括一些“怪癖”或意料之外的行为。因此,对外暴露的内容需要格外谨慎。
详情
作者的原始描述
Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.
repo: addyosmani/agent-skills
热度
- GitHub 星标
- 107k
- 排名
- #761
- 许可证
- MIT
- 更新时间
- 2026/10/13
评论
- …
同一仓库的更多技能
browser-testing-with-devtools
107k帮助你的智能体直接在真实浏览器中测试代码。适用于检查功能在实际使用环境中的表现,并发现错误和性能问题。
ci-cd-and-automation
107k教你的 AI 智能体自动化重复性任务、发布项目并管理基础设施。
code-review-and-quality
107k从多个角度对代码进行详细审查。适用于合并新改动之前,确保质量并避免日后出现问题。
code-simplification
107k简化代码,使其更易理解和维护。适用于代码能运行但过于复杂的情况,帮助提升清晰度。