API and Interface Design

Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or…

You say
Buy it · $69 Read it before you buy $69 Written by addyosmani · unverified publisher
Context cost
3.7k tokensestimated from the bundle, loaded when it triggers
Bundle
1 file · 14.9 kBtext throughout, nothing executable
Licence
MITpaid listing
Last change
no release on file
Servers it uses
Noneruns standalone

What it does

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.

Installed, it changes the agent in these ways.

What this skill changes about the agent is not written down here yet. The listing was collected from its source, and the description is in its own SKILL.md.

Workflow

Runs a procedure end to end.

apirest

The skill itself

This is the whole product. A skill is instructions the model reads, so there is nothing behind the listing you cannot see first — the front matter loads with every session, and the body below it loads when the skill triggers.

SKILL.md14.9 kB · 368 lines
--- 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. ---
6# API and Interface Design
7
8## Overview
9
10Design 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.
11
12## When to Use
13
14- Designing new API endpoints
15- Defining module boundaries or contracts between teams
16- Creating component prop interfaces
17- Establishing database schema that informs API shape
18- Changing existing public interfaces
19
20## Core Principles
21
22### Hyrum's Law
23
24> 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.
25
26This 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:
27
28- **Be intentional about what you expose.** Every observable behavior is a potential commitment.
29- **Don't leak implementation details.** If users can observe it, they will depend on it.
30- **Plan for deprecation at design time.** See deprecation-and-migration for how to safely remove things users depend on.
31- **Tests are not enough.** Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior.
32
33### The One-Version Rule
34
35Avoid 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.
36
37### 1. Contract First
38
39Define the interface before implementing it. The contract is the spec — implementation follows.
40
41```typescript
42// Define the contract first
43interface TaskAPI {
44 // Creates a task and returns the created task with server-generated fields
45 createTask(input: CreateTaskInput): Promise<Task>;
46
47 // Returns paginated tasks matching filters
48 listTasks(params: ListTasksParams): Promise<PaginatedResult<Task>>;
49
50 // Returns a single task or throws NotFoundError
51 getTask(id: string): Promise<Task>;
52
53 // Partial update — only provided fields change
54 updateTask(id: string, input: UpdateTaskInput): Promise<Task>;
55
56 // Idempotent delete — succeeds even if already deleted
57 deleteTask(id: string): Promise<void>;
58}
59```
60
61### 2. Consistent Error Semantics
62
63Pick one error strategy and use it everywhere:
64
65```typescript
66// REST: HTTP status codes + structured error body
67// Every error response follows the same shape
68interface APIError {
69 error: {
70 code: string; // Machine-readable: "VALIDATION_ERROR"
71 message: string; // Human-readable: "Email is required"
72 details?: unknown; // Additional context when helpful
73 };
74}
75
76// Status code mapping
77// 400 → Client sent invalid data
78// 401 → Not authenticated
79// 403 → Authenticated but not authorized
80// 404 → Resource not found
81// 409 → Conflict (duplicate, version mismatch)
82// 422 → Validation failed (semantically invalid)
83// 500 → Server error (never expose internal details)
84```
85
86**Don't mix patterns.** If some endpoints throw, others return null, and others return { error } — the consumer can't predict behavior.
87
88### 3. Validate at Boundaries
89
90Trust internal code. Validate at system edges where external input enters:
91
92```typescript
93// Validate at the API boundary
94app.post('/api/tasks', async (req, res) => {
95 const result = CreateTaskSchema.safeParse(req.body);
96 if (!result.success) {
97 return res.status(422).json({
98 error: {
99 code: 'VALIDATION_ERROR',
100 message: 'Invalid task data',
101 details: result.error.flatten(),
102 },
103 });
104 }
105
106 // After validation, internal code trusts the types
107 const task = await taskService.create(result.data);
108 return res.status(201).json(task);
109});
110```
111
112Where validation belongs:
113- API route handlers (user input)
114- Form submission handlers (user input)
115- External service response parsing (third-party data -- **always treat as untrusted**)
116- Environment variable loading (configuration)
117
118> **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.
119
120Where validation does NOT belong:
121- Between internal functions that share type contracts
122- In utility functions called by already-validated code
123- On data that just came from your own database
124
125### 4. Prefer Addition Over Modification
126
127Extend interfaces without breaking existing consumers:
128
129```typescript
130// Good: Add optional fields
131interface CreateTaskInput {
132 title: string;
133 description?: string;
134 priority?: 'low' | 'medium' | 'high'; // Added later, optional
135 labels?: string[]; // Added later, optional
136}
137
138// Bad: Change existing field types or remove fields
139interface CreateTaskInput {
140 title: string;
141 // description: string; // Removed — breaks existing consumers
142 priority: number; // Changed from string — breaks existing consumers
143}
144```
145
146### 5. Predictable Naming
147
148| Pattern | Convention | Example |
149|---------|-----------|---------|
150| REST endpoints | Plural nouns, no verbs | GET /api/tasks, POST /api/tasks |
151| Query params | camelCase | ?sortBy=createdAt&pageSize=20 |
152| Response fields | camelCase | { createdAt, updatedAt, taskId } |
153| Boolean fields | is/has/can prefix | isComplete, hasAttachments |
154| Enum values | UPPER_SNAKE | "IN_PROGRESS", "COMPLETED" |
155
156### 6. Honouring an Idempotency Key
157
158Accepting 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.
159
160**Derive the key from the intent, not the attempt.** The key must be stable across retries of one intent and different across distinct intents:
161
162```typescript
163crypto.randomUUID() // ✗ new key per attempt — every retry is a new charge
164${userId}:${amount} // ✗ two legitimate $50 charges collapse into one
165${orderId}:${Date.now()} // ✗ a timestamp is randomUUID() wearing a hat
166
167req.headers['idempotency-key'] // ✓ client generates once, reuses on retry
168charge:v1:${orderId} // ✓ derived from an immutable identifier
169```
170
171The key comes from the client or the initiating event — never from the layer doing the retrying.
172
173**Claim atomically. A check followed by an act is a race:**
174
175```typescript
176// ✗ TOCTOU: two concurrent retries both read "not seen", both charge
177if (!(await db.exists(key))) {
178 await chargeCard(amount);
179 await db.insert(key);
180}
181
182// ✓ let the unique constraint pick the winner
183try {
184 await db.insert({ key, state: 'in_progress', requestHash });
185} catch (e) {
186 if (isUniqueViolation(e)) return replayOrReject(key);
187 throw;
188}
189const result = await chargeCard(amount);
190await db.update({ key, state: 'succeeded', response: result });
191```
192
193The unique constraint *is* the mechanism. A store that cannot enforce uniqueness in one operation cannot back this.
194
195**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:
196
197```typescript
198if (existing.requestHash !== hash(req.body)) {
199 return res.status(422).json({ error: 'idempotency key reused with a different payload' });
200}
201```
202
203**Decide what an in-flight duplicate gets.** The first request is still running when the second arrives — the common case under retry storms:
204
205| Strategy | Response | Use when |
206|---|---|---|
207| Reject | 409 Conflict | Client can retry later; simplest and safest |
208| Wait | Block for the result, bounded | Caller needs it synchronously |
209| Return pending | 202 + status URL | Long-running effects |
210
211Never let the second caller through because the first "seems stuck". A stalled attempt whose fate is unknown is exactly when duplicating costs most.
212
213**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.
214
215**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.
216
217## REST API Patterns
218
219### Resource Design
220
221```
222GET /api/tasks → List tasks (with query params for filtering)
223POST /api/tasks → Create a task
224GET /api/tasks/:id → Get a single task
225PATCH /api/tasks/:id → Update a task (partial)
226DELETE /api/tasks/:id → Delete a task
227
228GET /api/tasks/:id/comments → List comments for a task (sub-resource)
229POST /api/tasks/:id/comments → Add a comment to a task
230```
231
232### Pagination
233
234Paginate list endpoints:
235
236```typescript
237// Request
238GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc
239
240// Response
241{
242 "data": [...],
243 "pagination": {
244 "page": 1,
245 "pageSize": 20,
246 "totalItems": 142,
247 "totalPages": 8
248 }
249}
250```
251
252### Filtering
253
254Use query parameters for filters:
255
256```
257GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01
258```
259
260### Partial Updates (PATCH)
261
262Accept partial objects — only update what's provided:
263
264```typescript
265// Only title changes, everything else preserved
266PATCH /api/tasks/123
267{ "title": "Updated title" }
268```
269
270## TypeScript Interface Patterns
271
272### Use Discriminated Unions for Variants
273
274```typescript
275// Good: Each variant is explicit
276type TaskStatus =
277 | { type: 'pending' }
278 | { type: 'in_progress'; assignee: string; startedAt: Date }
279 | { type: 'completed'; completedAt: Date; completedBy: string }
280 | { type: 'cancelled'; reason: string; cancelledAt: Date };
281
282// Consumer gets type narrowing
283function getStatusLabel(status: TaskStatus): string {
284 switch (status.type) {
285 case 'pending': return 'Pending';
286 case 'in_progress': return In progress (${status.assignee});
287 case 'completed': return Done on ${status.completedAt};
288 case 'cancelled': return Cancelled: ${status.reason};
289 }
290}
291```
292
293### Input/Output Separation
294
295```typescript
296// Input: what the caller provides
297interface CreateTaskInput {
298 title: string;
299 description?: string;
300}
301
302// Output: what the system returns (includes server-generated fields)
303interface Task {
304 id: string;
305 title: string;
306 description: string | null;
307 createdAt: Date;
308 updatedAt: Date;
309 createdBy: string;
310}
311```
312
313### Use Branded Types for IDs
314
315```typescript
316type TaskId = string & { readonly __brand: 'TaskId' };
317type UserId = string & { readonly __brand: 'UserId' };
318
319// Prevents accidentally passing a UserId where a TaskId is expected
320function getTask(id: TaskId): Promise<Task> { ... }
321```
322
323## Common Rationalizations
324
325| Rationalization | Reality |
326|---|---|
327| "We'll document the API later" | The types ARE the documentation. Define them first. |
328| "We don't need pagination for now" | You will the moment someone has 100+ items. Add it from the start. |
329| "PATCH is complicated, let's just use PUT" | PUT requires the full object every time. PATCH is what clients actually want. |
330| "We'll version the API when we need to" | Breaking changes without versioning break consumers. Design for extension from the start. |
331| "Nobody uses that undocumented behavior" | Hyrum's Law: if it's observable, somebody depends on it. Treat every public behavior as a commitment. |
332| "We can just maintain two versions" | Multiple versions multiply maintenance cost and create diamond dependency problems. Prefer the One-Version Rule. |
333| "Internal APIs don't need contracts" | Internal consumers are still consumers. Contracts prevent coupling and enable parallel work. |
334| "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. |
335| "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. |
336| "Duplicate requests are rare" | They're *correlated*. Retries spike exactly when a dependency is degraded — the moment duplicates are most likely and most expensive. |
337
338## Red Flags
339
340- Endpoints that return different shapes depending on conditions
341- Inconsistent error formats across endpoints
342- Validation scattered throughout internal code instead of at boundaries
343- Breaking changes to existing fields (type changes, removals)
344- List endpoints without pagination
345- Verbs in REST URLs (/api/createTask, /api/getUsers)
346- Third-party API responses used without validation or sanitization
347- A SELECT for an idempotency key followed by an INSERT — that's a race, not a guard
348- An idempotency key derived from a UUID, timestamp, or anything else regenerated per attempt
349- The same key accepted with a different request body, silently returning the first response
350- A key retention window shorter than the longest path that can re-deliver the request
351
352## Verification
353
354After designing an API:
355
356- [ ] Every endpoint has typed input and output schemas
357- [ ] Error responses follow a single consistent format
358- [ ] Validation happens at system boundaries only
359- [ ] List endpoints support pagination
360- [ ] New fields are additive and optional (backward compatible)
361- [ ] Naming follows consistent conventions across all endpoints
362- [ ] API documentation or types are committed alongside the implementation
363- [ ] State-changing endpoints either honour an idempotency key or are documented as unsafe to retry
364- [ ] The key is claimed in one atomic operation, guarded by a unique constraint
365- [ ] A reused key with a different payload fails loudly rather than replaying the wrong response
366- [ ] The in-flight-duplicate response is a deliberate choice (409, wait, or 202) rather than whatever falls out
367- [ ] Key retention outlives the longest retry path, including dead-letter replay
368
In the file
SKILL.md2,167 words
Files1
LicenceMIT
Why you can read it

Nothing in a skill executes. The client loads the text and the model follows it, so a skill can be audited the way a runbook is — by reading it.

What it costs in context

Skills are not billed by the call. They are paid for in context: every token the instructions occupy is a token your code, your diff and your conversation cannot use. Here is what this one takes and when it takes it.

≈80
always loaded
The name and description, so the model knows the skill exists and when to reach for it.
3,645
on trigger
The instruction body, read only when the skill fires.
1.9%
of a 200k window
Ten skills this size would take about 19% of the window before you open a file.
050k100k150k200k context window

3.7k tokens, estimated from the bundle at four bytes to the token, held for the rest of the session once it triggers. Middling. Fine to keep on in a project where you use it weekly, worth unloading in one where you never do.

Servers bill, skills cost

A server charges by the month. A skill charges once per session, in context, and then keeps charging it for as long as the session lives.

Before and after

The same question, put to the same model twice: once as it comes, and once with these instructions loaded.

No worked example has been published for this skill yet.

Adoption
Installsnone yet
Ratingno reviews yet

The procedure it runs

The procedure has not been published here. It is in the skill’s own SKILL.md, which its author has not sent to the marketplace yet.

Prose, not code

These steps are written for a model to follow, not executed by a runtime. It can still be told to skip one, and it will say so when it does.

Servers it uses

None. This skill calls no MCP servers at all.

Everything it needs is in the instructions, so it works in a project with nothing connected — the model reads the file and changes how it works with what it can already reach.

It writes no files and reaches no network. All it changes is how the model reasons and writes.

What it asks for
Writes filesno
Network accessno

Read from the allowed-tools line of this skill’s own SKILL.md. A skill grants no permissions of its own — it can only ask for tools your client already has.

What it will not do

Every skill is narrow, and the useful ones say where they stop. These are the jobs this one is the wrong tool for.

What this skill is not for has not been published here. Nothing is implied by that: it is a section the author has not filled in.

What is in the bundle

1 file, 14.9 kB on disk. A bundle is text throughout: the instructions the model reads, plus the templates it fills in.

  • SKILL.md14.9 kB
What is not in it

No dependencies and nothing executable: a skill is text the agent reads, so the bundle is 1 file you can review in full before installing. The MIT licence covers the templates and examples as well as the instructions.

Install

Installing copies the bundle into your project. Nothing runs at install time — the files sit on disk until the model reads them.

$69 once
API and Interface Design · MIT · addyosmani
one-time
Price$69 once
LicenceMIT — the author’s, unchanged by this purchase
Paid throughStripe, once, on the card you add at the checkout
Keeps workingfor good — the files are yours once they are on disk
Updatesevery update its author ships, delivered through this account

You can read the whole bundle before paying — the SKILL.md above is the product, not a preview of it. What the money buys is the delivery: the folder packaged and handed to your machine by key, every update its author ships, and our support if it does not do what this listing says. The terms of use are MIT, set by the author and unchanged by buying it here.

Payment runs through Stripe, on a page like this one rather than a redirect. Once there is an account it joins the same mcprush invoice as everything else you run, so there is never a second card to enter.

Which clients pick it up on their own

A skill is a folder of text. A client with a skills folder reads it without being told; everywhere else the same text works, it is just handed to the model rather than found.

Claude Code.claude/skills/
Claude Desktop
ChatGPT
Cursor.cursor/skills/
VS Code.github/skills/
Codex CLI.agents/skills/
Gemini CLI.gemini/skills/
Grok.grok/skills/
Zed.agents/skills/
Windsurf.windsurf/skills/
Agent SDK.claude/skills/
HTTP / API
This release
Versionnot versioned
Publishedno release date on file
Price$69
Referenceaddyosmani/api-and-interface-design

Versions

Its author publishes no version number, so there is nothing here to pin to: what you install is the folder as it stands today. Instructions change more often than APIs do — a skill can be rewritten entirely without anything it depends on moving.

v
  • No earlier releases have been published to the marketplace.
Pinning

Nothing to pin to: this skill carries no version number of its own. What you install is what the folder holds on the day you install it.

Reviews

no reviews yet · no installs yet

Nobody has reviewed this skill yet. The rating is the mean of the reviews written here, so there is none until somebody writes the first.

Who can post

Only accounts that have had the skill installed for fourteen days, so a review is written after living with it rather than after reading it. Publishers may reply once.

Publisher
Servers0