Skip to content
Skillpedia
APIs & servers (backend)107k Β· #761

api-and-interface-design

What it does

This guide helps create interfaces (like APIs or contracts between program parts) that are easy to use and hard to misuse. It teaches how to define how different software parts communicate clearly and stably.

When to use it

  • βœ“When creating new connections between programs (APIs).
  • βœ“When defining how different parts of the same program should communicate.
  • βœ“When planning how a program interacts with the user (graphical interface).

Skill link

https://github.com/addyosmani/agent-skills/blob/main/skills/api-and-interface-design/SKILL.md

Copy it and paste it into your AI (Claude, ChatGPT or Cursor), asking it to follow the instructions.

How to use

The easiest way: copy the message and paste it into your AI. It reads the skill and follows the instructions.

Ready-to-paste message

Use this skill to help me: https://github.com/addyosmani/agent-skills/blob/main/skills/api-and-interface-design/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
Want your AI to find skills like this on its own?Install the free Skillpedia MCP: one line, and it searches 15,000+ skills before each task.Install in 1 minute β†’

Example of what to ask your AI

β€œHelp me define how a user can create a new task in a system, specifying the title and description.”

5 new skills a week. 1 minute to read.

api-and-interface-design: full guide

Teams often write the code first and discover the shape of the interface later. By then other code, other teams or other apps already depend on it, and fixing a wrong field name or an inconsistent error format breaks someone. This skill makes your agent work the other way round: it defines the contract first, then builds behind it.

It covers REST endpoints, GraphQL schemas, TypeScript types between modules, and the boundary between frontend and backend. It sets rules for error formats, validation at the edges, pagination, naming and safe changes over time. It also has a long section on idempotency keys, which stop a retried request from charging a customer twice. It suits developers and non-programmers who direct an agent to build a backend, and who want the result to stay stable as it grows.

Use cases

A task app with a separate frontend

You are building a to-do app where a React frontend talks to a Node backend. Before any code, the agent writes the types for creating, listing, updating and deleting tasks, so both sides agree on field names and error shapes from day one.

Adding fields without breaking users

Your API is live and a client now wants priority and labels on tasks. The skill pushes the agent to add them as optional fields instead of changing existing ones, so apps already calling the API keep working without any update.

Making payment retries safe

Your checkout endpoint sometimes times out and the client retries. You ask the agent to review it. It checks that the idempotency key comes from the order, is claimed atomically, and that the same key with a different body is rejected.

Step by step

  1. 1Install the skill by placing its folder in ~/.claude/skills/api-and-interface-design/ (or your project's .claude/skills/), then start your agent in the project.
  2. 2Describe what the interface must do in plain words: who calls it, what they send and what they expect back. Mention whether it is REST, GraphQL or types between modules.
  3. 3Ask the agent to write the contract first, meaning types and endpoint list, and to stop there. Read it and correct names or missing cases before any implementation.
  4. 4Have the agent implement the endpoints behind that contract, with validation at the entry points and one consistent error format across all of them.
  5. 5Ask for a review against the skill's red flags: missing pagination, verbs in URLs, mixed error formats, unvalidated third-party data. Fix what it finds.

Example

What to ask

β€œDesign the API for a task manager. Users can create, list, update and delete tasks. Give me the contract first, with types and endpoints, before writing any implementation.”

What you get

The agent returns TypeScript types for CreateTaskInput and Task, plus a list of endpoints: GET and POST /api/tasks, and GET, PATCH and DELETE /api/tasks/:id. It adds paginated listing, one shared error shape with codes like VALIDATION_ERROR, and notes that new fields will be optional.

Tips

  • βœ“Review the contract before approving any implementation. Changing a type on paper costs nothing; changing it after other code uses it does not.
  • βœ“Do not skip pagination or error formats because the project is small. The skill treats them as cheap now and costly to add later.
  • βœ“The idempotency section matters for anything involving money or side effects. Do not accept a key that is a random UUID or timestamp created per attempt, because retries then look like new requests.
  • βœ“The skill designs the interface; it does not remove old behavior safely. For retiring fields, use a deprecation process, since users may depend on quirks you never documented.

Alternatives

  • fastapi-python

    Pick this when your backend is already in Python with FastAPI and you want help building the service itself, not designing the contract.

  • agent-arch-system-design

    Pick this when your question is bigger than one interface: overall architecture, comparing patterns and recording technical decisions, without changing existing code.

  • api-connector-builder

    Pick this when you need to add one more integration to a project that already has a pattern, instead of designing a new interface from scratch.

Questions and answers

Does this skill work for GraphQL as well as REST?

Its description lists both. The detailed patterns in the material, such as resource URLs, status codes and pagination, are REST-focused, while the principles about contracts, validation and optional additions apply to any interface.

Should I use PUT or PATCH for updates?

The skill prefers PATCH. It accepts a partial object and changes only the fields you send, while PUT needs the full object every time. It lists "PATCH is complicated" as a rationalization to avoid.

Do internal APIs need a contract too?

Yes. The skill says internal consumers are still consumers. A written contract prevents tight coupling and lets different people or agents work in parallel on both sides of the boundary.

How it works

It works by first defining how the communication should be (the 'contract') before writing the code. This ensures everyone understands the rules and avoids surprises.

Technical content (original SKILL.md)

Original text by the author, straight from GitHub.

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:

…

FAQ

What is an API?

An API is like a restaurant menu: it defines what you can order (functions) and how to order it (parameters), without needing to know how the kitchen (the program) prepares the dish.

Why is 'contract first' important?

It's like agreeing on the rules of a game before starting to play. If everyone knows the rules (the contract), the game (the program) flows better and avoids conflicts.

What is 'Hyrum's Law'?

It's the idea that if many people use something, they end up depending on all its details, even 'quirks' or unexpected behaviors. Therefore, it's best to be careful about what you expose.

Details

Original description by the author

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.

repo: addyosmani/agent-skills

Popularity

GitHub stars
107k
Ranking position
#761
License
MIT
Updated
10/13/2026

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills