---
title: "API and Interface Design: review, setup & limitations · Undominated.ai"
canonical: https://undominated.ai/skills/addyosmani-api-and-interface-design/
description: "Designs public interfaces so the right call is easy and a breaking change is explicit."
---

# API and Interface Design: review, setup & limitations · Undominated.ai

> Designs public interfaces so the right call is easy and a breaking change is explicit.

[← Explore all skills](/skills/)

DEVELOPMENT WORKFLOW / Addy Osmani

# API and Interface Design

Designs public interfaces so the right call is easy and a breaking change is explicit.

 [See setup guidance ↓](#setup)[Original source ↗](https://github.com/addyosmani/agent-skills/tree/1401c8b8030e023baeebb31781a6653fe8e93026/skills/api-and-interface-design)

SOURCE REVIEW

 Reviewed 2026-10-15
 Evidence 5 linked sources
 Publisher Addy Osmani
 Licence [MIT ↗](https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/LICENSE)
 Revision 1401c8b8030e
 [Read what was—and wasn’t—checked ↓](#review)

“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.”

 [Addy Osmani · upstream description ↗](https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/skills/api-and-interface-design/SKILL.md) Our analysis follows below.

01 / THE REASONING

## Why this made the selection.

 - The skill treats every observable behaviour as a commitment and tells the author to define the contract before the implementation.
- Idempotency keys are specified as something that must be claimed atomically, not checked and then used.

### A good fit for

 - Designing a REST or module boundary before coding it
- Adding pagination, one error shape, and boundary validation to a new endpoint
- Review an idempotent API contract under concurrent retries and payload reuse.

### Weigh up before choosing

 - Error strategies must not be mixed across endpoints.
- Breaking changes to existing fields are a red flag; the preferred change is addition.
- Validation belongs at the edge, not scattered through internal code.
- This review did not execute the skill.
- Trusting internal or database values assumes those boundaries are controlled; persisted external data and dynamic types may still need validation.
- Idempotency-key retention must cover every redelivery path, including dead-letter queues and provider dispute windows; a key can expire before the same intent returns.

02 / THE REVIEW RECORD

## What we actually inspected.

Source review has boundaries. A clear record is more useful than a “safe” badge.

### Material inspected

 - skills/api-and-interface-design/SKILL.md
- LICENSE
- README.md (installation command audit at the existing pin)

### Our findings

 - The pinned skill cites Hyrum's Law and says undocumented quirks, error text, timing, and ordering become contracts once users depend on them.
- REST names are plural nouns, query parameters are camelCase, and list endpoints are paginated from the start.
- An Idempotency-Key must be derived from the intent, supplied by the client or initiating event, and claimed atomically.
- The verification list requires typed input and output, one error format, and validation only at system boundaries.
- The guide distinguishes accepting an Idempotency-Key from honoring its intended semantics and notes that undocumented observable behavior can become a consumer dependency.

### Not established by this review

 - The skill was not executed inside a host agent.
- Not executed: it was not installed or run.

The review applies to the material and revision named here. A newer upstream release can change its behavior.

03 / PUT IT TO WORK

## Add a skill to your workflow.

[Upstream setup instructions ↗](https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/README.md)

DOCUMENTED COMMAND

 npx skills add addyosmani/agent-skills/skills/api-and-interface-design --skill api-and-interface-design Copy command ↗

Run in your terminal to choose your AI tools, project or global scope, and installation method. This short command follows the current upstream version; the review covers the revision shown above.

 Optional: install the reviewed revision

Keeps the original source and installer version where recorded, while leaving your AI tools and installation scope for you to choose.

 npx skills@1.7.1 add https://github.com/addyosmani/agent-skills/tree/1401c8b8030e023baeebb31781a6653fe8e93026/skills/api-and-interface-design --skill api-and-interface-design Copy reviewed-revision command ↗ - Choose your AI tools and project or global installation scope in Skills CLI. The review applies to the source revision shown on this page.
- Retain all supporting files; separately configure companion skills, runtimes and service credentials named in the definition.
- Review the resulting diff and use an isolated target before any migration, deployment, load test or warehouse operation.
- For manual installation instead, download the complete bundle from https://undominated.ai/resources/skills/addyosmani-api-and-interface-design/bundle.zip and extract it into a new directory. It holds SKILL.md unchanged at revision 1401c8b8, the upstream licence and an attribution file.
- Place the extracted directory in your host's documented skills directory, named api-and-interface-design. Keep SKILL.md and the licence together.

### Before you start

 - A repository and explicit API compatibility requirements; framework-specific documentation for the implementation.

### Compatibility

Agent Skills-compatible hosts

### Local Markdown instructions

 - Read existing endpoints and types
- Write the contract, not necessarily the implementation
- Edits public interfaces and may change persistent idempotency storage or downstream calls.

### Cost model

MIT licence; no account is named.

THE COMPLETE REVIEWED DEFINITION

## Read it before you reuse it.

Original source bytes, with attribution. Review the host-specific setup notes above.

 Copy definition ↗ [Download definition + licence ↗](/resources/skills/addyosmani-api-and-interface-design/bundle.zip)[Raw Markdown ↗](/resources/skills/addyosmani-api-and-interface-design/definition.md)
 ---
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.
---

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

```typescript
// 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:

```typescript
// 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:

```typescript
// 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:

```typescript
// 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 prefix | `isComplete`, `hasAttachments` |
| Enum values | UPPER_SNAKE | `"IN_PROGRESS"`, `"COMPLETED"` |

### 6. Honouring an Idempotency Key

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

**Derive the key from the intent, not the attempt.** The key must be stable across retries of one intent and different across distinct intents:

```typescript
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 initiating event — never from the layer doing the retrying.

**Claim atomically. A check followed by an act is a race:**

```typescript
// ✗ 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 e;
}
const result = await chargeCard(amount);
await db.update({ key, state: 'succeeded', response: result });
```

The unique constraint *is* the mechanism. A store that cannot enforce uniqueness in one operation cannot back this.

**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:

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

**Decide what an in-flight duplicate gets.** The first request is still running when the second arrives — the common case under retry storms:

| Strategy | Response | Use when |
|---|---|---|
| Reject | `409 Conflict` | Client can retry later; simplest and safest |
| Wait | Block for the result, bounded | Caller needs it synchronously |
| Return pending | `202` + status URL | Long-running effects |

Never let the second caller through because the first "seems stuck". A stalled attempt whose fate is unknown is exactly when duplicating costs most.

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

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

## 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:

```typescript
// 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:

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

## TypeScript Interface Patterns

### Use Discriminated Unions for Variants

```typescript
// 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

```typescript
// 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

```typescript
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

| Rationalization | Reality |
|---|---|
| "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. |
| "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. |
| "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. |
| "Duplicate requests are rare" | They're *correlated*. Retries spike exactly when a dependency is degraded — the moment duplicates are most likely and most expensive. |

## 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
- A `SELECT` for an idempotency key followed by an `INSERT` — that's a race, not a guard
- An idempotency key derived from a UUID, timestamp, or anything else regenerated per attempt
- The same key accepted with a different request body, silently returning the first response
- A key retention window shorter than the longest path that can re-deliver the request

## 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
- [ ] State-changing endpoints either honour an idempotency key or are documented as unsafe to retry
- [ ] The key is claimed in one atomic operation, guarded by a unique constraint
- [ ] A reused key with a different payload fails loudly rather than replaying the wrong response
- [ ] The in-flight-duplicate response is a deliberate choice (409, wait, or 202) rather than whatever falls out
- [ ] Key retention outlives the longest retry path, including dead-letter replay

The download contains SKILL.md . Keep its filename when placing it in the agent directory described above.

By **Addy Osmani**. [Exact upstream source ↗](https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/skills/api-and-interface-design/SKILL.md) · [Licence](/resources/skills/addyosmani-api-and-interface-design/LICENSE.txt) · [Attribution](/resources/skills/addyosmani-api-and-interface-design/ATTRIBUTION.txt)

SHA-256 e83d34f52ff12dd8a7c5134cd7e8140ea4541ec65e204f8a1e4cd366e30c4192

 Read the applicable licence MIT License

Copyright (c) 2025 Addy Osmani

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

04 / FOLLOW THE EVIDENCE

## The source trail.

Our notes are separate from the original resource. Check upstream before adopting a new version.

 - [Skill definition ↗](https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/skills/api-and-interface-design/SKILL.md) Checked 2026-10-14 https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/skills/api-and-interface-design/SKILL.md Supports: Workflow and stated scope
- [Repository licence ↗](https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/LICENSE) Checked 2026-10-14 https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/LICENSE Supports: Redistribution terms
- [Install instructions ↗](https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/README.md) Checked 2026-10-14 https://github.com/addyosmani/agent-skills/blob/1401c8b8030e023baeebb31781a6653fe8e93026/README.md Supports: Documented install command
- [Definition excerpt rechecked at the existing revision ↗](https://raw.githubusercontent.com/addyosmani/agent-skills/1401c8b8030e023baeebb31781a6653fe8e93026/skills/api-and-interface-design/SKILL.md) Checked 2026-10-15 https://raw.githubusercontent.com/addyosmani/agent-skills/1401c8b8030e023baeebb31781a6653fe8e93026/skills/api-and-interface-design/SKILL.md Supports: limitations, review
- [Installation-source command audit at the existing revision ↗](https://raw.githubusercontent.com/addyosmani/agent-skills/1401c8b8030e023baeebb31781a6653fe8e93026/README.md) Checked 2026-10-15 https://raw.githubusercontent.com/addyosmani/agent-skills/1401c8b8030e023baeebb31781a6653fe8e93026/README.md Supports: review

KEEP COMPARING

## Other approaches to consider.

Related by category or shared topics. These are alternatives to inspect, not a measured quality order.

 [### Adversarial Decision Review ↗ Submit a bounded artifact and its contract to an independent reviewer before accepting a consequential decision.](/skills/addyosmani-doubt-driven-development/)[### Bug Reproduction Brief ↗ Reduce an uncertain bug report to an evidence-backed failing fixture before repair.](/skills/github-bug-reproduction-brief/)[### C# / TypeScript API Contract Drift ↗ Compare C# controller and DTO contracts with TypeScript or JavaScript consumers in both directions.](/skills/github-api-breaking-change-detector/)

 [AI Tools ↗](/tools/)[Skills ↗](/skills/)[Agents ↗](/agents/)[MCP Servers ↗](/mcp-servers/)[Workflows ↗](/workflows/)

## Continue your investigation

 - [Choose a toolkit](/tools/)
- [Inspect execution hosts](/agents/)
- [Check tool access](/mcp-servers/)
- [Check project dependencies](/check-repo/)
