Communitygithub.com

API 與介面設計

指導穩定的 API 和介面設計。在設計 API、模組邊界或任何公開介面時使用。在建立 REST 或 GraphQL 端點、定義模組之間的型別合約,或建立前後端之間的邊界時使用。

API 與介面設計 是什麼?

此技能提供一套全面的指導原則,用於設計穩定、文件完善且難以誤用的 API 和介面。它涵蓋 REST API、GraphQL、模組邊界、元件屬性等。其核心原則包括:合約優先(Contract First)、一致的錯誤語意、在邊界處進行驗證、偏好新增而非修改,以及可預測的命名約定。技能深入探討了 Hyrum 定律的影響——指出 API 的所有可觀察行為最終都會被依賴——並提倡單一版本規則(One-Version Rule)以避免鑽石依賴問題。對於冪等性處理,它提供了詳細的實作指南,強調從意圖而非嘗試中導出冪等性金鑰,並使用唯一約束來防止競爭條件。此技能支援 Claude Code 等 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、模組邊界、元件屬性,以及任何一段程式碼與另一段程式碼溝通的介面。

使用時機

  • 設計新的 API 端點
  • 定義模組邊界或團隊間的合約
  • 建立元件屬性介面
  • 建立會影響 API 形式的資料庫 schema
  • 變更現有的公開介面

核心原則

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;
}
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用戶端可以稍後重試;最簡單且最安全
等待阻塞以等待結果,有界呼叫者需要同步取得
回傳 pending202 + 狀態 URL長時間運行的副作用

永遠不要因為第一個「看起來卡住了」就讓第二個呼叫者通過。命運未知的停滯嘗試正是重複成本最高的時候。

每個呼叫有三種結果,而不是兩種:成功、失敗和_未知_。 逾時無法告訴你副作用是否已套用。在呼叫外部之前記錄意圖,以便在呼叫和回應之間的崩潰留下證據,證明某件事必須稍後解決——而不是默默地重複收費。

根據最長的重試鏈設定保留期限,而不是根據磁碟成本。金鑰必須比任何可以重新傳遞相同意圖的路徑(包括一周後重播的死信佇列和任何提供者爭議窗口)更長壽。在七天 DLQ 背後的 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 後:

  • 每個端點都有型別的輸入和輸出 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.

相關技能