[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7DNE8EFS584NGMJFQSWMTWH":3,"skill-same:01M7DNE8EFS584NGMJFQSWMTWH":57},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":14,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7DNE8EFS584NGMJFQSWMTWH","api-and-interface-design",null,"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.","weisser-dev\u002Fagentic-skills","weisser-dev","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F35608570?v=4","01M7DNDYMBDEGQEG28HSH8Y3YV","Erik","01M7DNDYN2V00G8NFTK2KZ5WBT",0,"MIT","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fapi-and-interface-design\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fapi-and-interface-design\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: api-and-interface-design\ndescription: 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.\n---\n\n> Adapted copy of addyosmani\u002Fagent-skills (MIT) for local use; changes are listed in `UPSTREAM.md`.\n> Ground rules that override anything below: use only tools that are already installed in the project\n> (project scripts, `npx --no-install ...`); never let npx\u002Fpip\u002Fbrew download or install anything and never add\n> MCP servers on your own; do not fetch web pages or online docs and do not upload or post data anywhere;\n> never push, deploy, run migrations, flip feature flags or change shared systems without the user's explicit\n> instruction. Commands inside CI\u002Fworkflow examples are file content to write, not commands to run now.\n\n# API and Interface Design\n\n## Overview\n\nDesign 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.\n\n## When to Use\n\n- Designing new API endpoints\n- Defining module boundaries or contracts between teams\n- Creating component prop interfaces\n- Establishing database schema that informs API shape\n- Changing existing public interfaces\n\n## Core Principles\n\n### Hyrum's Law\n\n> 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.\n\nThis 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:\n\n- **Be intentional about what you expose.** Every observable behavior is a potential commitment.\n- **Don't leak implementation details.** If users can observe it, they will depend on it.\n- **Plan for deprecation at design time.** See `deprecation-and-migration` for how to safely remove things users depend on.\n- **Tests are not enough.** Even with perfect contract tests, Hyrum's Law means \"safe\" changes can break real users who depend on undocumented behavior.\n\n### The One-Version Rule\n\nAvoid 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.\n\n### 1. Contract First\n\nDefine the interface before implementing it. The contract is the spec — implementation follows.\n\n```typescript\n\u002F\u002F Define the contract first\ninterface TaskAPI {\n  \u002F\u002F Creates a task and returns the created task with server-generated fields\n  createTask(input: CreateTaskInput): Promise\u003CTask>;\n\n  \u002F\u002F Returns paginated tasks matching filters\n  listTasks(params: ListTasksParams): Promise\u003CPaginatedResult\u003CTask>>;\n\n  \u002F\u002F Returns a single task or throws NotFoundError\n  getTask(id: string): Promise\u003CTask>;\n\n  \u002F\u002F Partial update — only provided fields change\n  updateTask(id: string, input: UpdateTaskInput): Promise\u003CTask>;\n\n  \u002F\u002F Idempotent delete — succeeds even if already deleted\n  deleteTask(id: string): Promise\u003Cvoid>;\n}\n```\n\n### 2. Consistent Error Semantics\n\nPick one error strategy and use it everywhere:\n\n```typescript\n\u002F\u002F REST: HTTP status codes + structured error body\n\u002F\u002F Every error response follows the same shape\ninterface APIError {\n  error: {\n    code: string;        \u002F\u002F Machine-readable: \"VALIDATION_ERROR\"\n    message: string;     \u002F\u002F Human-readable: \"Email is required\"\n    details?: unknown;   \u002F\u002F Additional context when helpful\n  };\n}\n\n\u002F\u002F Status code mapping\n\u002F\u002F 400 → Client sent invalid data\n\u002F\u002F 401 → Not authenticated\n\u002F\u002F 403 → Authenticated but not authorized\n\u002F\u002F 404 → Resource not found\n\u002F\u002F 409 → Conflict (duplicate, version mismatch)\n\u002F\u002F 422 → Validation failed (semantically invalid)\n\u002F\u002F 500 → Server error (never expose internal details)\n```\n\n**Don't mix patterns.** If some endpoints throw, others return null, and others return `{ error }` — the consumer can't predict behavior.\n\n### 3. Validate at Boundaries\n\nTrust internal code. Validate at system edges where external input enters:\n\n```typescript\n\u002F\u002F Validate at the API boundary\napp.post('\u002Fapi\u002Ftasks', async (req, res) => {\n  const result = CreateTaskSchema.safeParse(req.body);\n  if (!result.success) {\n    return res.status(422).json({\n      error: {\n        code: 'VALIDATION_ERROR',\n        message: 'Invalid task data',\n        details: result.error.flatten(),\n      },\n    });\n  }\n\n  \u002F\u002F After validation, internal code trusts the types\n  const task = await taskService.create(result.data);\n  return res.status(201).json(task);\n});\n```\n\nWhere validation belongs:\n- API route handlers (user input)\n- Form submission handlers (user input)\n- External service response parsing (third-party data -- **always treat as untrusted**)\n- Environment variable loading (configuration)\n\n> **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.\n\nWhere validation does NOT belong:\n- Between internal functions that share type contracts\n- In utility functions called by already-validated code\n- On data that just came from your own database\n\n### 4. Prefer Addition Over Modification\n\nExtend interfaces without breaking existing consumers:\n\n```typescript\n\u002F\u002F Good: Add optional fields\ninterface CreateTaskInput {\n  title: string;\n  description?: string;\n  priority?: 'low' | 'medium' | 'high';  \u002F\u002F Added later, optional\n  labels?: string[];                       \u002F\u002F Added later, optional\n}\n\n\u002F\u002F Bad: Change existing field types or remove fields\ninterface CreateTaskInput {\n  title: string;\n  \u002F\u002F description: string;  \u002F\u002F Removed — breaks existing consumers\n  priority: number;         \u002F\u002F Changed from string — breaks existing consumers\n}\n```\n\n### 5. Predictable Naming\n\n| Pattern | Convention | Example |\n|---------|-----------|---------|\n| REST endpoints | Plural nouns, no verbs | `GET \u002Fapi\u002Ftasks`, `POST \u002Fapi\u002Ftasks` |\n| Query params | camelCase | `?sortBy=createdAt&pageSize=20` |\n| Response fields | camelCase | `{ createdAt, updatedAt, taskId }` |\n| Boolean fields | is\u002Fhas\u002Fcan prefix | `isComplete`, `hasAttachments` |\n| Enum values | UPPER_SNAKE | `\"IN_PROGRESS\"`, `\"COMPLETED\"` |\n\n### 6. Honouring an Idempotency Key\n\nAccepting an `Idempotency-Key` is the contract. Honouring it is the implementation, and it is where the money is lost — a key the server accepts but handles carelessly is worse than no key at all, because the client now believes retrying is safe.\n\n**Derive the key from the intent, not the attempt.** The key must be stable across retries of one intent and different across distinct intents:\n\n```typescript\ncrypto.randomUUID()                    \u002F\u002F ✗ new key per attempt — every retry is a new charge\n`${userId}:${amount}`                  \u002F\u002F ✗ two legitimate $50 charges collapse into one\n`${orderId}:${Date.now()}`             \u002F\u002F ✗ a timestamp is randomUUID() wearing a hat\n\nreq.headers['idempotency-key']         \u002F\u002F ✓ client generates once, reuses on retry\n`charge:v1:${orderId}`                 \u002F\u002F ✓ derived from an immutable identifier\n```\n\nThe key comes from the client or the initiating event — never from the layer doing the retrying.\n\n**Claim atomically. A check followed by an act is a race:**\n\n```typescript\n\u002F\u002F ✗ TOCTOU: two concurrent retries both read \"not seen\", both charge\nif (!(await db.exists(key))) {\n  await chargeCard(amount);\n  await db.insert(key);\n}\n\n\u002F\u002F ✓ let the unique constraint pick the winner\ntry {\n  await db.insert({ key, state: 'in_progress', requestHash });\n} catch (e) {\n  if (isUniqueViolation(e)) return replayOrReject(key);\n  throw e;\n}\nconst result = await chargeCard(amount);\nawait db.update({ key, state: 'succeeded', response: result });\n```\n\nThe unique constraint *is* the mechanism. A store that cannot enforce uniqueness in one operation cannot back this.\n\n**Guard the payload.** Same key with a different body is a client bug, and must fail loudly rather than serving the first response to a second request:\n\n```typescript\nif (existing.requestHash !== hash(req.body)) {\n  return res.status(422).json({ error: 'idempotency key reused with a different payload' });\n}\n```\n\n**Decide what an in-flight duplicate gets.** The first request is still running when the second arrives — the common case under retry storms:\n\n| Strategy | Response | Use when |\n|---|---|---|\n| Reject | `409 Conflict` | Client can retry later; simplest and safest |\n| Wait | Block for the result, bounded | Caller needs it synchronously |\n| Return pending | `202` + status URL | Long-running effects |\n\nNever let the second caller through because the first \"seems stuck\". A stalled attempt whose fate is unknown is exactly when duplicating costs most.\n\n**Every call has three outcomes, not two: success, failure, and _unknown_.** A timeout tells you nothing about whether the effect applied. Record the intent *before* calling out, so a crash between the call and the response leaves evidence something must resolve later — rather than a silently retried charge.\n\n**Set retention from the longest retry chain**, not from disk cost. Keys must outlive every path that can re-deliver the same intent, including a dead-letter queue replayed a week later and any provider dispute window. A 24-hour key TTL behind a 7-day DLQ is a duplicate waiting to happen.\n\n## REST API Patterns\n\n### Resource Design\n\n```\nGET    \u002Fapi\u002Ftasks              → List tasks (with query params for filtering)\nPOST   \u002Fapi\u002Ftasks              → Create a task\nGET    \u002Fapi\u002Ftasks\u002F:id          → Get a single task\nPATCH  \u002Fapi\u002Ftasks\u002F:id          → Update a task (partial)\nDELETE \u002Fapi\u002Ftasks\u002F:id          → Delete a task\n\nGET    \u002Fapi\u002Ftasks\u002F:id\u002Fcomments → List comments for a task (sub-resource)\nPOST   \u002Fapi\u002Ftasks\u002F:id\u002Fcomments → Add a comment to a task\n```\n\n### Pagination\n\nPaginate list endpoints:\n\n```typescript\n\u002F\u002F Request\nGET \u002Fapi\u002Ftasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc\n\n\u002F\u002F Response\n{\n  \"data\": [...],\n  \"pagination\": {\n    \"page\": 1,\n    \"pageSize\": 20,\n    \"totalItems\": 142,\n    \"totalPages\": 8\n  }\n}\n```\n\n### Filtering\n\nUse query parameters for filters:\n\n```\nGET \u002Fapi\u002Ftasks?status=in_progress&assignee=user123&createdAfter=2025-01-01\n```\n\n### Partial Updates (PATCH)\n\nAccept partial objects — only update what's provided:\n\n```typescript\n\u002F\u002F Only title changes, everything else preserved\nPATCH \u002Fapi\u002Ftasks\u002F123\n{ \"title\": \"Updated title\" }\n```\n\n## TypeScript Interface Patterns\n\n### Use Discriminated Unions for Variants\n\n```typescript\n\u002F\u002F Good: Each variant is explicit\ntype TaskStatus =\n  | { type: 'pending' }\n  | { type: 'in_progress'; assignee: string; startedAt: Date }\n  | { type: 'completed'; completedAt: Date; completedBy: string }\n  | { type: 'cancelled'; reason: string; cancelledAt: Date };\n\n\u002F\u002F Consumer gets type narrowing\nfunction getStatusLabel(status: TaskStatus): string {\n  switch (status.type) {\n    case 'pending': return 'Pending';\n    case 'in_progress': return `In progress (${status.assignee})`;\n    case 'completed': return `Done on ${status.completedAt}`;\n    case 'cancelled': return `Cancelled: ${status.reason}`;\n  }\n}\n```\n\n### Input\u002FOutput Separation\n\n```typescript\n\u002F\u002F Input: what the caller provides\ninterface CreateTaskInput {\n  title: string;\n  description?: string;\n}\n\n\u002F\u002F Output: what the system returns (includes server-generated fields)\ninterface Task {\n  id: string;\n  title: string;\n  description: string | null;\n  createdAt: Date;\n  updatedAt: Date;\n  createdBy: string;\n}\n```\n\n### Use Branded Types for IDs\n\n```typescript\ntype TaskId = string & { readonly __brand: 'TaskId' };\ntype UserId = string & { readonly __brand: 'UserId' };\n\n\u002F\u002F Prevents accidentally passing a UserId where a TaskId is expected\nfunction getTask(id: TaskId): Promise\u003CTask> { ... }\n```\n\n## Common Rationalizations\n\n| Rationalization | Reality |\n|---|---|\n| \"We'll document the API later\" | The types ARE the documentation. Define them first. |\n| \"We don't need pagination for now\" | You will the moment someone has 100+ items. Add it from the start. |\n| \"PATCH is complicated, let's just use PUT\" | PUT requires the full object every time. PATCH is what clients actually want. |\n| \"We'll version the API when we need to\" | Breaking changes without versioning break consumers. Design for extension from the start. |\n| \"Nobody uses that undocumented behavior\" | Hyrum's Law: if it's observable, somebody depends on it. Treat every public behavior as a commitment. |\n| \"We can just maintain two versions\" | Multiple versions multiply maintenance cost and create diamond dependency problems. Prefer the One-Version Rule. |\n| \"Internal APIs don't need contracts\" | Internal consumers are still consumers. Contracts prevent coupling and enable parallel work. |\n| \"Accepting the Idempotency-Key header is enough\" | The header is the contract; storing the key against the result is the implementation. A key you accept but don't honour tells the client retrying is safe when it isn't. |\n| \"Our queue guarantees exactly-once delivery\" | No queue does across a consumer crash — the broker's ack and your side effect are not in one transaction. Design for at-least-once with idempotent processing. |\n| \"Duplicate requests are rare\" | They're *correlated*. Retries spike exactly when a dependency is degraded — the moment duplicates are most likely and most expensive. |\n\n## Red Flags\n\n- Endpoints that return different shapes depending on conditions\n- Inconsistent error formats across endpoints\n- Validation scattered throughout internal code instead of at boundaries\n- Breaking changes to existing fields (type changes, removals)\n- List endpoints without pagination\n- Verbs in REST URLs (`\u002Fapi\u002FcreateTask`, `\u002Fapi\u002FgetUsers`)\n- Third-party API responses used without validation or sanitization\n- A `SELECT` for an idempotency key followed by an `INSERT` — that's a race, not a guard\n- An idempotency key derived from a UUID, timestamp, or anything else regenerated per attempt\n- The same key accepted with a different request body, silently returning the first response\n- A key retention window shorter than the longest path that can re-deliver the request\n\n## Verification\n\nAfter designing an API:\n\n- [ ] Every endpoint has typed input and output schemas\n- [ ] Error responses follow a single consistent format\n- [ ] Validation happens at system boundaries only\n- [ ] List endpoints support pagination\n- [ ] New fields are additive and optional (backward compatible)\n- [ ] Naming follows consistent conventions across all endpoints\n- [ ] API documentation or types are committed alongside the implementation\n- [ ] State-changing endpoints either honour an idempotency key or are documented as unsafe to retry\n- [ ] The key is claimed in one atomic operation, guarded by a unique constraint\n- [ ] A reused key with a different payload fails loudly rather than replaying the wrong response\n- [ ] The in-flight-duplicate response is a deliberate choice (409, wait, or 202) rather than whatever falls out\n- [ ] Key retention outlives the longest retry path, including dead-letter replay\n","> Adapted copy of addyosmani\u002Fagent-skills (MIT) for local use; changes are listed in `UPSTREAM.md`.\n> Ground rules that override anything below: use only tools that are already installed in the project\n> (project scripts, `npx --no-install ...`); never let npx\u002Fpip\u002Fbrew download or install anything and never add\n> MCP servers on your own; do not fetch web pages or online docs and do not upload or post data anywhere;\n> never push, deploy, run migrations, flip feature flags or change shared systems without the user's explicit\n> instruction. Commands inside CI\u002Fworkflow examples are file content to write, not commands to run now.\n\n# API and Interface Design\n\n## Overview\n\nDesign 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.\n\n## When to Use\n\n- Designing new API endpoints\n- Defining module boundaries or contracts between teams\n- Creating component prop interfaces\n- Establishing database schema that informs API shape\n- Changing existing public interfaces\n\n## Core Principles\n\n### Hyrum's Law\n\n> 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.\n\nThis 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:\n\n- **Be intentional about what you expose.** Every observable behavior is a potential commitment.\n- **Don't leak implementation details.** If users can observe it, they will depend on it.\n- **Plan for deprecation at design time.** See `deprecation-and-migration` for how to safely remove things users depend on.\n- **Tests are not enough.** Even with perfect contract tests, Hyrum's Law means \"safe\" changes can break real users who depend on undocumented behavior.\n\n### The One-Version Rule\n\nAvoid 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.\n\n### 1. Contract First\n\nDefine the interface before implementing it. The contract is the spec — implementation follows.\n\n```typescript\n\u002F\u002F Define the contract first\ninterface TaskAPI {\n  \u002F\u002F Creates a task and returns the created task with server-generated fields\n  createTask(input: CreateTaskInput): Promise\u003CTask>;\n\n  \u002F\u002F Returns paginated tasks matching filters\n  listTasks(params: ListTasksParams): Promise\u003CPaginatedResult\u003CTask>>;\n\n  \u002F\u002F Returns a single task or throws NotFoundError\n  getTask(id: string): Promise\u003CTask>;\n\n  \u002F\u002F Partial update — only provided fields change\n  updateTask(id: string, input: UpdateTaskInput): Promise\u003CTask>;\n\n  \u002F\u002F Idempotent delete — succeeds even if already deleted\n  deleteTask(id: string): Promise\u003Cvoid>;\n}\n```\n\n### 2. Consistent Error Semantics\n\nPick one error strategy and use it everywhere:\n\n```typescript\n\u002F\u002F REST: HTTP status codes + structured error body\n\u002F\u002F Every error response follows the same shape\ninterface APIError {\n  error: {\n    code: string;        \u002F\u002F Machine-readable: \"VALIDATION_ERROR\"\n    message: string;     \u002F\u002F Human-readable: \"Email is required\"\n    details?: unknown;   \u002F\u002F Additional context when helpful\n  };\n}\n\n\u002F\u002F Status code mapping\n\u002F\u002F 400 → Client sent invalid data\n\u002F\u002F 401 → Not authenticated\n\u002F\u002F 403 → Authenticated but not authorized\n\u002F\u002F 404 → Resource not found\n\u002F\u002F 409 → Conflict (duplicate, version mismatch)\n\u002F\u002F 422 → Validation failed (semantically invalid)\n\u002F\u002F 500 → Server error (never expose internal details)\n```\n\n**Don't mix patterns.** If some endpoints throw, others return null, and others return `{ error }` — the consumer can't predict behavior.\n\n### 3. Validate at Boundaries\n\nTrust internal code. Validate at system edges where external input enters:\n\n```typescript\n\u002F\u002F Validate at the API boundary\napp.post('\u002Fapi\u002Ftasks', async (req, res) => {\n  const result = CreateTaskSchema.safeParse(req.body);\n  if (!result.success) {\n    return res.status(422).json({\n      error: {\n        code: 'VALIDATION_ERROR',\n        message: 'Invalid task data',\n        details: result.error.flatten(),\n      },\n    });\n  }\n\n  \u002F\u002F After validation, internal code trusts the types\n  const task = await taskService.create(result.data);\n  return res.status(201).json(task);\n});\n```\n\nWhere validation belongs:\n- API route handlers (user input)\n- Form submission handlers (user input)\n- External service response parsing (third-party data -- **always treat as untrusted**)\n- Environment variable loading (configuration)\n\n> **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.\n\nWhere validation does NOT belong:\n- Between internal functions that share type contracts\n- In utility functions called by already-validated code\n- On data that just came from your own database\n\n### 4. Prefer Addition Over Modification\n\nExtend interfaces without breaking existing consumers:\n\n```typescript\n\u002F\u002F Good: Add optional fields\ninterface CreateTaskInput {\n  title: string;\n  description?: string;\n  priority?: 'low' | 'medium' | 'high';  \u002F\u002F Added later, optional\n  labels?: string[];                       \u002F\u002F Added later, optional\n}\n\n\u002F\u002F Bad: Change existing field types or remove fields\ninterface CreateTaskInput {\n  title: string;\n  \u002F\u002F description: string;  \u002F\u002F Removed — breaks existing consumers\n  priority: number;         \u002F\u002F Changed from string — breaks existing consumers\n}\n```\n\n### 5. Predictable Naming\n\n| Pattern | Convention | Example |\n|---------|-----------|---------|\n| REST endpoints | Plural nouns, no verbs | `GET \u002Fapi\u002Ftasks`, `POST \u002Fapi\u002Ftasks` |\n| Query params | camelCase | `?sortBy=createdAt&pageSize=20` |\n| Response fields | camelCase | `{ createdAt, updatedAt, taskId }` |\n| Boolean fields | is\u002Fhas\u002Fcan prefix | `isComplete`, `hasAttachments` |\n| Enum values | UPPER_SNAKE | `\"IN_PROGRESS\"`, `\"COMPLETED\"` |\n\n### 6. Honouring an Idempotency Key\n\nAccepting an `Idempotency-Key` is the contract. Honouring it is the implementation, and it is where the money is lost — a key the server accepts but handles carelessly is worse than no key at all, because the client now believes retrying is safe.\n\n**Derive the key from the intent, not the attempt.** The key must be stable across retries of one intent and different across distinct intents:\n\n```typescript\ncrypto.randomUUID()                    \u002F\u002F ✗ new key per attempt — every retry is a new charge\n`${userId}:${amount}`                  \u002F\u002F ✗ two legitimate $50 charges collapse into one\n`${orderId}:${Date.now()}`             \u002F\u002F ✗ a timestamp is randomUUID() wearing a hat\n\nreq.headers['idempotency-key']         \u002F\u002F ✓ client generates once, reuses on retry\n`charge:v1:${orderId}`                 \u002F\u002F ✓ derived from an immutable identifier\n```\n\nThe key comes from the client or the initiating event — never from the layer doing the retrying.\n\n**Claim atomically. A check followed by an act is a race:**\n\n```typescript\n\u002F\u002F ✗ TOCTOU: two concurrent retries both read \"not seen\", both charge\nif (!(await db.exists(key))) {\n  await chargeCard(amount);\n  await db.insert(key);\n}\n\n\u002F\u002F ✓ let the unique constraint pick the winner\ntry {\n  await db.insert({ key, state: 'in_progress', requestHash });\n} catch (e) {\n  if (isUniqueViolation(e)) return replayOrReject(key);\n  throw e;\n}\nconst result = await chargeCard(amount);\nawait db.update({ key, state: 'succeeded', response: result });\n```\n\nThe unique constraint *is* the mechanism. A store that cannot enforce uniqueness in one operation cannot back this.\n\n**Guard the payload.** Same key with a different body is a client bug, and must fail loudly rather than serving the first response to a second request:\n\n```typescript\nif (existing.requestHash !== hash(req.body)) {\n  return res.status(422).json({ error: 'idempotency key reused with a different payload' });\n}\n```\n\n**Decide what an in-flight duplicate gets.** The first request is still running when the second arrives — the common case under retry storms:\n\n| Strategy | Response | Use when |\n|---|---|---|\n| Reject | `409 Conflict` | Client can retry later; simplest and safest |\n| Wait | Block for the result, bounded | Caller needs it synchronously |\n| Return pending | `202` + status URL | Long-running effects |\n\nNever let the second caller through because the first \"seems stuck\". A stalled attempt whose fate is unknown is exactly when duplicating costs most.\n\n**Every call has three outcomes, not two: success, failure, and _unknown_.** A timeout tells you nothing about whether the effect applied. Record the intent *before* calling out, so a crash between the call and the response leaves evidence something must resolve later — rather than a silently retried charge.\n\n**Set retention from the longest retry chain**, not from disk cost. Keys must outlive every path that can re-deliver the same intent, including a dead-letter queue replayed a week later and any provider dispute window. A 24-hour key TTL behind a 7-day DLQ is a duplicate waiting to happen.\n\n## REST API Patterns\n\n### Resource Design\n\n```\nGET    \u002Fapi\u002Ftasks              → List tasks (with query params for filtering)\nPOST   \u002Fapi\u002Ftasks              → Create a task\nGET    \u002Fapi\u002Ftasks\u002F:id          → Get a single task\nPATCH  \u002Fapi\u002Ftasks\u002F:id          → Update a task (partial)\nDELETE \u002Fapi\u002Ftasks\u002F:id          → Delete a task\n\nGET    \u002Fapi\u002Ftasks\u002F:id\u002Fcomments → List comments for a task (sub-resource)\nPOST   \u002Fapi\u002Ftasks\u002F:id\u002Fcomments → Add a comment to a task\n```\n\n### Pagination\n\nPaginate list endpoints:\n\n```typescript\n\u002F\u002F Request\nGET \u002Fapi\u002Ftasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc\n\n\u002F\u002F Response\n{\n  \"data\": [...],\n  \"pagination\": {\n    \"page\": 1,\n    \"pageSize\": 20,\n    \"totalItems\": 142,\n    \"totalPages\": 8\n  }\n}\n```\n\n### Filtering\n\nUse query parameters for filters:\n\n```\nGET \u002Fapi\u002Ftasks?status=in_progress&assignee=user123&createdAfter=2025-01-01\n```\n\n### Partial Updates (PATCH)\n\nAccept partial objects — only update what's provided:\n\n```typescript\n\u002F\u002F Only title changes, everything else preserved\nPATCH \u002Fapi\u002Ftasks\u002F123\n{ \"title\": \"Updated title\" }\n```\n\n## TypeScript Interface Patterns\n\n### Use Discriminated Unions for Variants\n\n```typescript\n\u002F\u002F Good: Each variant is explicit\ntype TaskStatus =\n  | { type: 'pending' }\n  | { type: 'in_progress'; assignee: string; startedAt: Date }\n  | { type: 'completed'; completedAt: Date; completedBy: string }\n  | { type: 'cancelled'; reason: string; cancelledAt: Date };\n\n\u002F\u002F Consumer gets type narrowing\nfunction getStatusLabel(status: TaskStatus): string {\n  switch (status.type) {\n    case 'pending': return 'Pending';\n    case 'in_progress': return `In progress (${status.assignee})`;\n    case 'completed': return `Done on ${status.completedAt}`;\n    case 'cancelled': return `Cancelled: ${status.reason}`;\n  }\n}\n```\n\n### Input\u002FOutput Separation\n\n```typescript\n\u002F\u002F Input: what the caller provides\ninterface CreateTaskInput {\n  title: string;\n  description?: string;\n}\n\n\u002F\u002F Output: what the system returns (includes server-generated fields)\ninterface Task {\n  id: string;\n  title: string;\n  description: string | null;\n  createdAt: Date;\n  updatedAt: Date;\n  createdBy: string;\n}\n```\n\n### Use Branded Types for IDs\n\n```typescript\ntype TaskId = string & { readonly __brand: 'TaskId' };\ntype UserId = string & { readonly __brand: 'UserId' };\n\n\u002F\u002F Prevents accidentally passing a UserId where a TaskId is expected\nfunction getTask(id: TaskId): Promise\u003CTask> { ... }\n```\n\n## Common Rationalizations\n\n| Rationalization | Reality |\n|---|---|\n| \"We'll document the API later\" | The types ARE the documentation. Define them first. |\n| \"We don't need pagination for now\" | You will the moment someone has 100+ items. Add it from the start. |\n| \"PATCH is complicated, let's just use PUT\" | PUT requires the full object every time. PATCH is what clients actually want. |\n| \"We'll version the API when we need to\" | Breaking changes without versioning break consumers. Design for extension from the start. |\n| \"Nobody uses that undocumented behavior\" | Hyrum's Law: if it's observable, somebody depends on it. Treat every public behavior as a commitment. |\n| \"We can just maintain two versions\" | Multiple versions multiply maintenance cost and create diamond dependency problems. Prefer the One-Version Rule. |\n| \"Internal APIs don't need contracts\" | Internal consumers are still consumers. Contracts prevent coupling and enable parallel work. |\n| \"Accepting the Idempotency-Key header is enough\" | The header is the contract; storing the key against the result is the implementation. A key you accept but don't honour tells the client retrying is safe when it isn't. |\n| \"Our queue guarantees exactly-once delivery\" | No queue does across a consumer crash — the broker's ack and your side effect are not in one transaction. Design for at-least-once with idempotent processing. |\n| \"Duplicate requests are rare\" | They're *correlated*. Retries spike exactly when a dependency is degraded — the moment duplicates are most likely and most expensive. |\n\n## Red Flags\n\n- Endpoints that return different shapes depending on conditions\n- Inconsistent error formats across endpoints\n- Validation scattered throughout internal code instead of at boundaries\n- Breaking changes to existing fields (type changes, removals)\n- List endpoints without pagination\n- Verbs in REST URLs (`\u002Fapi\u002FcreateTask`, `\u002Fapi\u002FgetUsers`)\n- Third-party API responses used without validation or sanitization\n- A `SELECT` for an idempotency key followed by an `INSERT` — that's a race, not a guard\n- An idempotency key derived from a UUID, timestamp, or anything else regenerated per attempt\n- The same key accepted with a different request body, silently returning the first response\n- A key retention window shorter than the longest path that can re-deliver the request\n\n## Verification\n\nAfter designing an API:\n\n- [ ] Every endpoint has typed input and output schemas\n- [ ] Error responses follow a single consistent format\n- [ ] Validation happens at system boundaries only\n- [ ] List endpoints support pagination\n- [ ] New fields are additive and optional (backward compatible)\n- [ ] Naming follows consistent conventions across all endpoints\n- [ ] API documentation or types are committed alongside the implementation\n- [ ] State-changing endpoints either honour an idempotency key or are documented as unsafe to retry\n- [ ] The key is claimed in one atomic operation, guarded by a unique constraint\n- [ ] A reused key with a different payload fails loudly rather than replaying the wrong response\n- [ ] The in-flight-duplicate response is a deliberate choice (409, wait, or 202) rather than whatever falls out\n- [ ] Key retention outlives the longest retry path, including dead-letter replay\n",{"name":5,"description":7},"main","4e619808b53adf347c8e9ba357c1150cc228cc06","skills\u002Fapi-and-interface-design","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills","https:\u002F\u002Fgithub.com\u002Fweisser-dev","weisser.dev","Tech Lead AI \u002F Senior Solution Architect · GenAI platforms, agents, homelab","2026-10-03 23:10:36",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add weisser-dev\u002Fagentic-skills --skill api-and-interface-design",{"tool":39,"command":40},"bunx","bunx skills add weisser-dev\u002Fagentic-skills --skill api-and-interface-design",{"tool":42,"command":43},"pnpm","pnpm dlx skills add weisser-dev\u002Fagentic-skills --skill api-and-interface-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fapi-and-interface-design\u002FSKILL.md",true,[47,51],{"path":48,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":16},"LICENSE","许可证",1068,{"path":52,"resourceType":53,"resourceTypeDesc":54,"sizeBytes":55,"sourceHtmlUrl":56},"UPSTREAM.md","REFERENCE","参考文档",1064,"https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fapi-and-interface-design\u002FUPSTREAM.md",[58,65,73,81,89,97],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":20},"01M7DQF4DKN0VPGNYTKAYX1BNB","web-design-guidelines","Review UI code against the Web Interface Guidelines (accessibility, focus, forms, motion, typography, performance, copy). Use when asked to review a UI, check accessibility, audit a design or UX, or check a site against best practices.","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fweb-design-guidelines\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":69,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":20},"01M7DQF0NF4548JFK6V6RDHECF","using-agent-skills","Discovers and invokes agent skills. Use when starting a session, or when you need to decide which skill or workflow applies to the piece of work at hand. This is the meta-skill that governs how all other skills are discovered and invoked.","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fusing-agent-skills\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fusing-agent-skills\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":77,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":20},"01M7DQETRD811BNNW6922HEWNK","test-driven-development","Drives development with tests using the red-green-refactor loop. Use when implementing any logic, fixing any bug, or changing any behavior. Use when you need to prove that code works, when a bug report arrives, or when you're about to modify existing functionality.","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Ftest-driven-development\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":85,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":20},"01M7DQEMPANA6WNEK8FTSPGH7S","spec-driven-development","Creates specs before coding. Use when starting a new project, feature, or significant change and no specification exists yet. Use when drafting a PRD or requirements document with objectives and scope, or when requirements are unclear, ambiguous, or only exist as a vague idea. Use when a single requirement spans several independently testable capabilities and needs decomposing into a capability map of modules before specifying.","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fspec-driven-development\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fspec-driven-development\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":20},"01M7DQEFYF0K35689XGPQHJTPV","shipping-and-launch","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.","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fshipping-and-launch\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fshipping-and-launch\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":101,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":20},"01M7DQE86FE58Y4R00T8Q4HRR5","security-and-hardening","Hardens code against vulnerabilities. Use when auditing an input handler for vulnerabilities, when handling user input, authentication, data storage, or external integrations, or when checking a login flow is safe against the OWASP Top Ten. Use when building any feature that accepts untrusted data, manages user sessions, or interacts with third-party services. Use when auditing dependencies for known vulnerabilities, triaging package-manager audit findings, or assessing supply-chain risk in a new package. Use when personal data or privacy compliance (GDPR, CCPA) is involved.","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsecurity-and-hardening\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fweisser-dev\u002Fagentic-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsecurity-and-hardening\u002FSKILL.md",[],[]]