SuperAPI AI Directory

api-and-interface-design

Coding & development

View repository

Updated 10-16 08:53

About this skill

API and Interface Design

Overview

Design interfaces that are stable, clearly documented, and 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 a new API endpoint
  • Defining module boundaries or contracts between teams
  • Creating component prop interfaces
  • Establishing database schemas that affect API shape
  • Modifying existing public interfaces

Core Principles

Hyrum's Law

With enough API users, all observable behavior in a system will be depended on by someone, regardless of what you promised 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:

  • Deliberately decide what to expose. Every observable behavior is a potential promise.
  • Do not leak implementation details. If users can observe it, they will depend on it.
  • Plan for deprecation at design time. For how to safely remove something users depend on, see deprecation-and-migration。
  • Testing is not enough. Even with perfect contract tests, Hyrum's Law means "safe" changes can still break real users who depend on undocumented behavior.

Single-Version Rule

Avoid forcing consumers to choose between multiple versions of the same dependency or API. The diamond dependency problem arises when different consumers need different versions of the same thing. Design for a world where only one version exists at a time: extend, do not fork.

1. Contract First

Define the interface first, then implement it. The contract is the specification, and the 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

Choose 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)

Do not mix patterns. If some endpoints throw, some return null, and some return { error }, consumers cannot predict behavior.

3. Validate at the Boundary

Trust internal code. Validate at the edge where external input enters the system:

// 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);
});

Validation should go in:

  • 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 abnormal external service may return unexpected types, malicious content, or instruction-like text.

Validation should not go in:

  • Between internal functions that share a type contract
  • In utility functions called by already-validated code
  • On data just fetched from your own database

4. Prefer Addition Over Modification

Extend interfaces without breaking existing consumers:

// Good: Add optional fields
interface CreateTaskInput {
  title: string;
  description?: string;
  priority?: 'low' | 'medium' | 'high';  // Added later, optional
  labels?: string[];                       // Added later, optional
}

// Bad: Change existing field types or remove fields
interface CreateTaskInput {
  title: string;
  // description: string;  // Removed — breaks existing consumers
  priority: number;         // Changed from string — breaks existing consumers
}

5. Predictable Naming

Pattern Convention Example
REST endpoints Plural nouns, no verbs GET /api/tasks, POST /api/tasks
Query params camelCase ?sortBy=createdAt&pageSize=20
Response fields camelCase { createdAt, updatedAt, taskId }
Boolean fields is/has/can prefixes isComplete, hasAttachments
Enum values UPPER_SNAKE "IN_PROGRESS", "COMPLETED"

6. Honor the Idempotency Key

Accepting Idempotency-Key is a contract; honoring it is the implementation, and this is exactly where the money gets lost. A server that accepts the key but handles it carelessly is worse than having no key at all, because the client now believes retries are safe.

Derive the key from the intent, not from a single attempt. The key must remain stable across multiple retries of the same intent, and must differ between different intents:

crypto.randomUUID()                    // ✗ new key per attempt — every retry is a new charge
`${userId}:${amount}`                  // ✗ two legitimate $50 charges collapse into one
`${orderId}:${Date.now()}`             // ✗ a timestamp is randomUUID() wearing a hat

req.headers['idempotency-key']         // ✓ client generates once, reuses on retry
`charge:v1:${orderId}`                 // ✓ derived from an immutable identifier

The key comes from the client or the originating event, never from the layer responsible for retrying.

Claim atomically. Check-then-act is a race:

// ✗ TOCTOU: two concurrent retries both read "not seen", both charge
if (!(await db.exists(key))) {
  await chargeCard(amount);
  await db.insert(key);
}

// ✓ let the unique constraint pick the winner
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 });

unique constraint isthis mechanism. A store that cannot enforce uniqueness in a single operation cannot support this design.

Guard the payload. The same key paired with a different body is a client bug and must fail loudly, rather than sending the first response straight to the second request:

if (existing.requestHash !== hash(req.body)) {
  return res.status(422).json({ error: 'idempotency key reused with a different payload' });
}

Think through what an in-flight duplicate request will get. The second request arrives while the first is still executing, which is the norm under a retry storm:

Strategy Response Applicable scenario
Reject 409 Conflict The client can retry later; simplest and safest
Wait Block waiting for the result, with an upper bound The caller needs the result synchronously
Return pending 202 + status URL Long-running side effects

Never let a second caller through just because the first request "looks stuck". A stalled attempt with an unknown outcome is precisely the moment when duplicate execution costs the most.

Every call has three outcomes, not two: success, failure, and unknown。 . A timeout does not tell you whether the side effect has already taken effect. Before making the callbeforehand, record the intent first, so that if a crash happens between the call and the response, there is evidence that "something is pending" rather than letting a charge be silently retried.

The retention period depends on the longest retry chain, not on disk cost. The key must outlive all paths that could redeliver the same intent, including a dead-letter queue replayed a week later and any provider dispute window. A 7-day DLQ paired with a 24-hour key TTL means duplicate execution is only a matter of time.

REST API Patterns

Resource Design

GET    /api/tasks              → List tasks (with query params for filtering)
POST   /api/tasks              → Create a task
GET    /api/tasks/:id          → Get a single task
PATCH  /api/tasks/:id          → Update a task (partial)
DELETE /api/tasks/:id          → Delete a task

GET    /api/tasks/:id/comments → List comments for a task (sub-resource)
POST   /api/tasks/:id/comments → Add a comment to a task

Pagination

Paginate list endpoints:

// Request
GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc

// Response
{
  "data": [...],
  "pagination": {
    "page": 1,
    "pageSize": 20,
    "totalItems": 142,
    "totalPages": 8
  }
}

Filtering

Use query parameters for filters:

GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01

Partial Updates (PATCH)

Accept partial objects and update only the provided fields:

// Only title changes, everything else preserved
PATCH /api/tasks/123
{ "title": "Updated title" }

TypeScript Interface Patterns

Use Discriminated Unions for Variants

// Good: Each variant is explicit
type TaskStatus =
  | { type: 'pending' }
  | { type: 'in_progress'; assignee: string; startedAt: Date }
  | { type: 'completed'; completedAt: Date; completedBy: string }
  | { type: 'cancelled'; reason: string; cancelledAt: Date };

// Consumer gets type narrowing
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}`;
  }
}

Separate Input/Output

// Input: what the caller provides
interface CreateTaskInput {
  title: string;
  description?: string;
}

// Output: what the system returns (includes server-generated fields)
interface Task {
  id: string;
  title: string;
  description: string | null;
  createdAt: Date;
  updatedAt: Date;
  createdBy: string;
}

Use Branded Types for IDs

type TaskId = string & { readonly __brand: 'TaskId' };
type UserId = string & { readonly __brand: 'UserId' };

// Prevents accidentally passing a UserId where a TaskId is expected
function getTask(id: TaskId): Promise<Task> { ... }

Common Self-Justifications

Self-Justification Reality
"We'll write the API docs later" The types are the documentation. Define them first.
"We don't need pagination yet" As soon as someone has 100+ items, it's needed immediately. Add it from the start.
"PATCH is complex, let's just use PUT" PUT requires sending the complete object every time. PATCH is what clients actually want.
"Version the API when needed" Breaking changes without versioning will break consumers. Design for extension from the start.
"Nobody uses that undocumented behavior" Hyrum's Law: if it's observable, someone will depend on it. Treat every public behavior as a promise.
"We can maintain two versions at the same time" Multiple versions amplify maintenance costs and create diamond dependency problems. Prefer a single-version rule.
"Internal APIs don't need contracts" Internal consumers are consumers too. Contracts prevent coupling and support parallel work.
"Accepting the Idempotency-Key header is enough" The header is the contract; storing the key together with the result is the implementation. A key that is accepted but not honored tells clients retries are safe when they are not.
"Our queue guarantees exactly-once delivery" No queue can do that when a consumer crashes. The broker's ack and your side effect are not in the same transaction. Design for at-least-once plus idempotent processing.
"Duplicate requests are rare" They arecorrelated. Retries spike exactly when dependencies degrade, which is precisely when duplicates are most likely and most costly.

Red flags

  • Endpoint returns different shapes based on conditions
  • Error formats are inconsistent across endpoints
  • Validation is scattered in internal code instead of at the boundary
  • Breaking changes to existing fields (type changes, removals)
  • List endpoints have no pagination
  • Verbs in REST URLs (/api/createTask、/api/getUsers)
  • Using third-party API responses without validation or sanitization
  • Using SELECT to look up the idempotency key and then INSERT, that's a race, not a guard
  • Idempotency key derived from a UUID, timestamp, or any value regenerated on every attempt
  • Accepting the same key with a different request body but silently returning the first response
  • Key retention window shorter than the longest path on which a request may be redelivered

Validation

After designing the API:

  • Every endpoint has typed input and output schemas
  • Error responses follow a single consistent format
  • Validation happens only at system boundaries
  • List endpoints support pagination
  • New fields are additive and optional (backward compatible)
  • Naming follows consistent conventions across all endpoints
  • API documentation or types are committed together with the implementation
  • Endpoints that change state either honor idempotency keys or document that retries are unsafe
  • Claiming a key is an atomic operation protected by a unique constraint
  • Reusing a key with a different payload fails loudly instead of replaying the wrong response
  • The response to in-flight duplicate requests is intentionally chosen (409, wait, or 202), rather than whichever behavior happens to occur
  • The key retention period is longer than the longest retry path, including dead-letter replay