api-and-interface-design

작성자: addyosmani

안정적인 API 및 인터페이스 설계를 안내합니다. API, 모듈 경계 또는 공개 인터페이스를 설계할 때 사용하세요. REST나 GraphQL 엔드포인트를 생성하거나, 모듈 간 타입 계약을 정의하거나, 프론트엔드와 백엔드 간 경계를 설정할 때 사용하세요.

npx skills add https://github.com/addyosmani/agent-skills --skill api-and-interface-design

API and Interface Design

Overview

Design 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.

When to Use

  • Designing new API endpoints
  • Defining module boundaries or contracts between teams
  • Creating component prop interfaces
  • Establishing database schema that informs API shape
  • Changing existing public interfaces

Core Principles

Hyrum's Law

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.

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:

  • Be intentional about what you expose. Every observable behavior is a potential commitment.
  • Don't leak implementation details. If users can observe it, they will depend on it.
  • Plan for deprecation at design time. See deprecation-and-migration for how to safely remove things users depend on.
  • Tests are not enough. Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior.

The One-Version Rule

Avoid 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.

1. Contract First

Define the interface before implementing it. The contract is the spec — 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

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

Don't mix patterns. If some endpoints throw, others return null, and others return { error } — the consumer can't predict behavior.

3. Validate at Boundaries

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

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

Where validation belongs:

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

Where validation does NOT belong:

  • Between internal functions that share type contracts
  • In utility functions called by already-validated code
  • On data that just came 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

PatternConventionExample
REST endpointsPlural nouns, no verbsGET /api/tasks, POST /api/tasks
Query paramscamelCase?sortBy=createdAt&pageSize=20
Response fieldscamelCase{ createdAt, updatedAt, taskId }
Boolean fieldsis/has/can prefixisComplete, hasAttachments
Enum valuesUPPER_SNAKE"IN_PROGRESS", "COMPLETED"

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 — only update what's provided:

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

Input/Output Separation

// 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 Rationalizations

RationalizationReality
"We'll document the API later"The types ARE the documentation. Define them first.
"We don't need pagination for now"You will the moment someone has 100+ items. Add it from the start.
"PATCH is complicated, let's just use PUT"PUT requires the full object every time. PATCH is what clients actually want.
"We'll version the API when we need to"Breaking changes without versioning break consumers. Design for extension from the start.
"Nobody uses that undocumented behavior"Hyrum's Law: if it's observable, somebody depends on it. Treat every public behavior as a commitment.
"We can just maintain two versions"Multiple versions multiply maintenance cost and create diamond dependency problems. Prefer the One-Version Rule.
"Internal APIs don't need contracts"Internal consumers are still consumers. Contracts prevent coupling and enable parallel work.

Red Flags

  • Endpoints that return different shapes depending on conditions
  • Inconsistent error formats across endpoints
  • Validation scattered throughout internal code instead of at boundaries
  • Breaking changes to existing fields (type changes, removals)
  • List endpoints without pagination
  • Verbs in REST URLs (/api/createTask, /api/getUsers)
  • Third-party API responses used without validation or sanitization

Verification

After designing an API:

  • Every endpoint has typed input and output schemas
  • Error responses follow a single consistent format
  • Validation happens at system boundaries only
  • 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 alongside the implementation

addyosmani의 다른 스킬

accessibility
addyosmani
WCAG 2.2 지침에 따라 웹 접근성을 감사하고 개선합니다. "접근성 개선", "a11y 감사", "WCAG 준수", "스크린 리더 지원", "키보드 탐색", "접근 가능하게 만들기"와 같은 요청이 있을 때 사용하세요.
developmenttestingcode-review
web-quality-audit
addyosmani
성능, 접근성, SEO 및 모범 사례를 포괄하는 종합적인 웹 품질 감사입니다. "내 사이트 감사", "웹 품질 검토", "라이트하우스 감사 실행", "페이지 품질 확인", "내 웹사이트 최적화" 요청 시 사용하세요.
developmenttestingresearch
seo
addyosmani
검색 엔진 가시성과 순위를 최적화합니다. "SEO 개선", "검색 최적화", "메타 태그 수정", "구조화된 데이터 추가", "사이트맵 최적화", 또는 "검색 엔진 최적화"를 요청받을 때 사용하세요.
marketingresearchdevelopment
performance
addyosmani
웹 성능을 최적화하여 더 빠른 로딩과 더 나은 사용자 경험을 제공합니다. "사이트 속도 높이기", "성능 최적화", "로딩 시간 줄이기", "느린 로딩 수정", "페이지 속도 개선", "성능 감사" 요청 시 사용하세요.
developmenttesting
code-review-and-quality
addyosmani
다축 코드 리뷰를 수행합니다. 변경 사항을 병합하기 전에 사용하세요. 자신, 다른 에이전트 또는 사람이 작성한 코드를 검토할 때 사용하세요. 코드가 메인 브랜치에 들어가기 전에 여러 차원에서 코드 품질을 평가해야 할 때 사용하세요.
developmentcode-review
frontend-ui-engineering
addyosmani
프로덕션 품질의 접근 가능하고 반응형 사용자 인터페이스를 구축합니다. 인터페이스나 페이지를 만들거나 수정할 때, 컴포넌트를 생성할 때, 레이아웃을 구현할 때, WCAG 접근성 요구사항을 충족할 때, 상태를 관리할 때, 또는 결과물이 AI 생성물처럼 보이지 않고 프로덕션 품질처럼 보여야 할 때 사용하세요.
developmentdesign
security-and-hardening
addyosmani
코드를 취약점으로부터 강화합니다. 사용자 입력, 인증, 데이터 저장소 또는 외부 통합을 처리할 때 사용하세요. 신뢰할 수 없는 데이터를 받거나, 사용자 세션을 관리하거나, 타사 서비스와 상호작용하는 모든 기능을 구축할 때 사용하세요.
spec-driven-development
addyosmani
코딩 전에 명세를 작성합니다. 새 프로젝트, 기능 또는 중요한 변경을 시작할 때 아직 명세가 없는 경우 사용합니다. 요구사항이 불명확하거나, 모호하거나, 막연한 아이디어로만 존재할 때 사용합니다.
developmentdocumentproject-management