跳到正文
Skillpedia
API 与服务器(后端)107k · #761

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。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/addyosmani/agent-skills/blob/main/skills/api-and-interface-design/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 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-migration for 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

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能