{"id":20322,"plugin_id":"plugins_6aa30973082881919357c0ce8d85a8eb","kind":"skill","collection_source":null,"comparison_source":null,"observed_at":"2026-09-30T23:16:11.960Z","digest":"c415d184bb90dbc36b795ac436e2885aa4c75a55657c0cfb0f1917cff7f8aa5e","against":null,"payload":{"name":"api-and-interface-design","description":"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.","included_files":[],"skill_md_contents":"---\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.\ndisable-model-invocation: true\n---\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// Define the contract first\ninterface TaskAPI {\n  // Creates a task and returns the created task with server-generated fields\n  createTask(input: CreateTaskInput): Promise<Task>;\n\n  // Returns paginated tasks matching filters\n  listTasks(params: ListTasksParams): Promise<PaginatedResult<Task>>;\n\n  // Returns a single task or throws NotFoundError\n  getTask(id: string): Promise<Task>;\n\n  // Partial update — only provided fields change\n  updateTask(id: string, input: UpdateTaskInput): Promise<Task>;\n\n  // Idempotent delete — succeeds even if already deleted\n  deleteTask(id: string): Promise<void>;\n}\n```\n\n### 2. Consistent Error Semantics\n\nPick one error strategy and use it everywhere:\n\n```typescript\n// REST: HTTP status codes + structured error body\n// Every error response follows the same shape\ninterface APIError {\n  error: {\n    code: string;        // Machine-readable: \"VALIDATION_ERROR\"\n    message: string;     // Human-readable: \"Email is required\"\n    details?: unknown;   // Additional context when helpful\n  };\n}\n\n// Status code mapping\n// 400 → Client sent invalid data\n// 401 → Not authenticated\n// 403 → Authenticated but not authorized\n// 404 → Resource not found\n// 409 → Conflict (duplicate, version mismatch)\n// 422 → Validation failed (semantically invalid)\n// 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// Validate at the API boundary\napp.post('/api/tasks', 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  // 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// Good: Add optional fields\ninterface CreateTaskInput {\n  title: string;\n  description?: string;\n  priority?: 'low' | 'medium' | 'high';  // Added later, optional\n  labels?: string[];                       // Added later, optional\n}\n\n// Bad: Change existing field types or remove fields\ninterface CreateTaskInput {\n  title: string;\n  // description: string;  // Removed — breaks existing consumers\n  priority: number;         // 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 /api/tasks`, `POST /api/tasks` |\n| Query params | camelCase | `?sortBy=createdAt&pageSize=20` |\n| Response fields | camelCase | `{ createdAt, updatedAt, taskId }` |\n| Boolean fields | is/has/can 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()                    // ✗ new key per attempt — every retry is a new charge\n`${userId}:${amount}`                  // ✗ two legitimate $50 charges collapse into one\n`${orderId}:${Date.now()}`             // ✗ a timestamp is randomUUID() wearing a hat\n\nreq.headers['idempotency-key']         // ✓ client generates once, reuses on retry\n`charge:v1:${orderId}`                 // ✓ 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// ✗ 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// ✓ 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;\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    /api/tasks              → List tasks (with query params for filtering)\nPOST   /api/tasks              → Create a task\nGET    /api/tasks/:id          → Get a single task\nPATCH  /api/tasks/:id          → Update a task (partial)\nDELETE /api/tasks/:id          → Delete a task\n\nGET    /api/tasks/:id/comments → List comments for a task (sub-resource)\nPOST   /api/tasks/:id/comments → Add a comment to a task\n```\n\n### Pagination\n\nPaginate list endpoints:\n\n```typescript\n// Request\nGET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc\n\n// 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 /api/tasks?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// Only title changes, everything else preserved\nPATCH /api/tasks/123\n{ \"title\": \"Updated title\" }\n```\n\n## TypeScript Interface Patterns\n\n### Use Discriminated Unions for Variants\n\n```typescript\n// 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// 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/Output Separation\n\n```typescript\n// Input: what the caller provides\ninterface CreateTaskInput {\n  title: string;\n  description?: string;\n}\n\n// 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// Prevents accidentally passing a UserId where a TaskId is expected\nfunction getTask(id: TaskId): Promise<Task> { ... }\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 (`/api/createTask`, `/api/getUsers`)\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"},"changes":[],"summary":"First saved snapshot. No earlier version is available for comparison.","summary_kind":"deterministic","summary_metadata":{}}