agentleFS
int2t05int2t05/engineering-skills/skills/03-design/api-design/SKILL.md

api-design

Skill3 starsChanged 4 months agoMITView on GitHub

Use when designing APIs or interfaces — REST/GraphQL contracts, request/response shapes, versioning, error models, and interface ergonomics. Triggers on "design API", "REST contract", "GraphQL schema", "接口设计", "API 契约", "API 设计".

125 other projects use a version of this, 1 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use data-modeling, ci-pipeline and 6 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • mmondoraSkill

    data-modeling

    Schema design, multi-tenant data isolation, and migration management. Firestore and PostgreSQL patterns, RLS, UUID v7 conventions. Use when designing database schemas, writing migrations, or implementing multi-tenant data access.

    Also in 7 projects that use this

  • vndeeSkill

    ci-pipeline

    Use when creating or updating CI/CD pipelines with GitHub Actions or GitLab CI for Go, Python, or React projects

    Also in 4 projects that use this

  • pluginagentmarketplaceSkill

    microservices

    Microservices architecture patterns and best practices. Service decomposition, inter-service communication, and distributed data management.

    Also in 4 projects that use this

  • kevinaimonsterSkill

    typescript-strict

    TypeScript strict mode and advanced type system assistant. Helps write strictly-typed TypeScript code with generics, type guards, utility types, conditional types, mapped types, and template literal types. Trigger when user says 'TypeScript types' 'type gymnastics' 'TypeScript generics' 'strict TypeScript' 'type guard' 'TS类型' 'TypeScript严格模式' '类型体操' '泛型怎么写' 'TS type help'. Keywords: TypeScript, strict mode, generics, type guard, utility types, conditional types, mapped types, template literal types, infer, extends, keyof, typeof, type narrowing, discriminated unions, type assertion, type predicate, type gymnastics, TS, 类型体操, 泛型, 类型守卫, 严格类型

    Also in 4 projects that use this

  • InfopibeSkill

    deployment-patterns

    Deployment workflows, CI/CD pipeline patterns, Docker containerization, health checks, rollback strategies, and production readiness checklists for web applications.

    Also in 10 projects that use this

  • CloudAI-XSkill

    database-design

    Designs database schemas, indexing strategies, query optimization, and migration patterns for SQL and NoSQL databases. Use when designing tables, optimizing queries, fixing N+1 problems, planning migrations, or when asked about database performance, normalization, ORMs, or data modeling.

    Also in 15 projects that use this

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 1 is distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 104 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    The One-Version Rule: Avoid forcing consumers to choose between multiple versions.

    line 37
  2. Very specific:

    Every error response follows the same shape.

    line 47

“Common” is measured: kept by at least 6 in 10 of the 104 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

API and Interface Design

Design stable, well-documented interfaces that are hard to misuse. Good interfaces make the right thing easy and the wrong thing hard. 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 REST or GraphQL endpoints
  • Defining module boundaries or contracts between teams
  • Creating component prop interfaces or type contracts
  • Establishing database schema that informs API shape
  • Changing existing public interfaces
  • Triggers on "API design", "interface design", "REST", "GraphQL", "contract", "接口设计", "API 契约", "API 设计"

Not for: system-level architecture decisions (use architecture); deep-module or codebase structure (use codebase-design).

Steps

1. Define the contract first

The contract is the spec — implementation follows. Define typed input and output schemas before writing handlers. The types ARE the documentation.

2. Apply core principles

Hyrum's Law: With enough users, all observable behaviors become de-facto contracts — including undocumented quirks, error text, timing, and ordering. Be intentional about what you expose; don't leak implementation details; plan for deprecation at design time.

The One-Version Rule: Avoid forcing consumers to choose between multiple versions. Design for a world where only one version exists at a time — extend rather than fork. Multiple versions multiply maintenance cost and create diamond dependency problems.

Addition Over Modification: Extend interfaces without breaking consumers — add optional fields, never change existing field types or remove fields. Breaking changes without versioning break consumers.

3. Pick one error strategy and use it everywhere

Every error response follows the same shape. Don't mix patterns — if some endpoints throw, others return null, and others return { error }, the consumer can't predict behavior.

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 malformed request (can't parse — bad JSON, wrong content-type), 401 not authenticated, 403 not authorized, 404 not found, 409 conflict (duplicate, version mismatch), 422 well-formed but semantically invalid (fails business validation), 500 server error (never expose internal details).

4. Validate at boundaries

Trust internal code. Validate at system edges where external input enters: API route handlers, form submissions, external service response parsing (third-party data is always untrusted), and environment variable loading. Do NOT validate between internal functions that share type contracts, in utility functions called by already-validated code, or on data from your own database.

5. Follow 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"

6. Apply REST resource patterns

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 (idempotent)
GET    /api/tasks/:id/comments → List comments for a task (sub-resource)

Paginate every list endpoint from the start — you will need it the moment someone has 100+ items. Accept partial objects on PATCH (only update what's provided), not full objects on PUT.

7. Use discriminated unions for variants

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 — each variant is explicit, no optional fields that don't apply. Separate input types (what the caller provides) from output types (what the system returns, including server-generated fields). Use branded types for IDs to prevent accidentally passing a UserId where a TaskId is expected.

Output: docs/API/*.md — one file per endpoint group, with full request/response shapes, parameters, errors, and examples.

Verify

  • Every endpoint has typed input and output schemas
  • Error responses follow a single consistent format across all endpoints
  • Validation happens at system boundaries only, not scattered through internal code
  • 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

Red flags: endpoints that return different shapes depending on conditions; inconsistent error formats; validation scattered through internal code; breaking changes to existing fields; list endpoints without pagination; verbs in REST URLs (/api/createTask); third-party API responses used without validation.

Common rationalizations: "We'll document later" — the types ARE the documentation, define them first. "We don't need pagination for now" — add it from the start. "PATCH is complicated, use PUT" — PATCH is what clients actually want. "We'll version when we need to" — design for extension from the start. "Nobody uses that undocumented behavior" — Hyrum's Law says someone does.

References

  • ${CLAUDE_PLUGIN_ROOT}/references/engineering-principles.md — shared discipline (enforce simplicity, surgical scope, verify don't assume)
  • references/versioning-strategy.md — when breaking change is unavoidable: URI/header versioning, sunset/deprecation headers (RFC 8594), dual-version coexistence, sunset timeline
  • references/openapi-lifecycle.md — design-first vs code-first, Spectral/Redocly linting, openapi-generator SDK generation, spec versioning, CI pipeline

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.