Community程式設計與開發github.com

API 與介面設計

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

API 與介面設計 是什麼?

此技能依據經過驗證的軟體工程原則,提供設計穩定、易於使用且難以誤用的 API 和介面的全面指引。它涵蓋 REST API、GraphQL 架構、模組邊界、元件 props 以及任何程式碼間的通訊表面。核心原則包括合約優先開發、一致的錯誤語意、在邊界進行驗證、偏好擴充而非修改、可預測的命名,以及冪等性金鑰的正確實作。此技能特別重視 Hyrum 定律,強調所有可觀察的行為都會成為事實上的合約,並詳細解釋冪等性金鑰的陷阱與正確實作模式,包括原子性宣告、酬載防護,以及處理飛行中重複請求的策略。它也涵蓋實用的 REST API 模式(資源設計、分頁、過濾、部分更新)和 TypeScript 介面模式(辨別式聯合、輸入/輸出分離、品牌型別)。此技能適用於任何使用 API 或定義介面的平台,包括 Claude Code、Cursor 和 Codex 等 AI 代理工具,幫助開發者建立更可靠、更易維護的系統。

相容平台~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 架構、模組邊界、元件 props,以及任何一段程式碼與另一段程式碼通訊的表面。

使用時機

  • 設計新的 API 端點
  • 定義模組邊界或團隊間的合約
  • 建立元件 prop 介面
  • 建立影響 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 天 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 後:

  • 每個端點都有型別的輸入和輸出架構
  • 錯誤回應遵循單一且一致的格式
  • 驗證僅在系統邊界進行
  • 列表端點支援分頁
  • 新欄位是附加且可選的(向後相容)
  • 命名在所有端點間遵循一致的慣例
  • 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).

相關技能