agentleFS
krzysztofsurdykrzysztofsurdy/code-virtuoso/skills/knowledge/api-design/SKILL.md

api-design

Skill22 starsChanged 9 months agoMITView on GitHub

REST and GraphQL API design principles for consistent, predictable, and evolvable APIs. Use when the user asks to design a new API, review an existing API, choose between REST and GraphQL, plan API versioning, define error response contracts, implement pagination, or establish API standards for a team. Covers resource modeling, endpoint naming, HTTP methods, status codes, authentication patterns, rate limiting, HATEOAS, and API evolution strategies.

125 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use data-modeling, ci-pipeline and 8 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

  • 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

  • DatabricksSkill

    load-testing

    Load test a Databricks App to find its maximum QPS. Use when: (1) User says 'load test', 'benchmark', 'QPS', 'throughput', or 'performance test', (2) User wants to find how many queries per second their app can handle, (3) User wants to set up load testing scripts for their agent, (4) User wants to view load test results/dashboard, (5) User wants to validate results or observe latency/error rate with MLflow tracing.

    Also in 4 projects that use this

  • benshapyroSkill

    react-patterns

    Modern React patterns for TypeScript applications including hooks, state management, and component composition. Use when building React components, managing state, or implementing React best practices.

    Also in 9 projects that use this

The file

Show its rules and text

We split this skill into the rules it gives an agent

16 rules. 0 are common, 13 are distinctive, and 3 are very specific to this project.

  • 0

    Common

    Most of the 104 edited versions we read keep these.

  • 13

    Distinctive

    This author's own choices. Worth a look.

  • 3

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use plural nouns for collections: /users, /users/{id}

    line 53
  2. Distinctive:

    Use HTTP status codes meaningfully — do not return 200 for everything

    line 55
  3. Distinctive:

    Use the type system to enforce constraints (non-null, enums, input types)

    line 82
  4. Distinctive:

    Avoid deeply nested schemas that create unpredictable query costs

    line 83
  5. Very specific:

    Use a machine-readable type or code — clients should branch on codes, not messages

    line 139
  6. Distinctive:

    Use appropriate HTTP status codes (REST) or structured error types (GraphQL)

    line 142
  7. Distinctive:

    Never expose stack traces, internal paths, or SQL queries in production

    line 143
  8. Distinctive:

    Only bump the major version for breaking changes

    line 175
  9. Distinctive:

    Prefer evolving the API additively (new fields, new endpoints) over creating new versions

    line 176
  10. Distinctive:

    When a version is deprecated, communicate a sunset date and provide migration guides

    line 177
  11. Distinctive:

    Every list endpoint needs pagination.

    line 183
  12. Very specific:

    If totalCount is expensive, make it optional or return an estimate

    line 193
  13. Distinctive:

    Use cursors for feeds, activity streams, and any data that changes frequently

    line 194
  14. Distinctive:

    Use offset for admin dashboards, reports, and datasets that rarely change during browsing

    line 195
  15. Distinctive:

    Always use HTTPS — no exceptions

    line 223
  16. Distinctive:

    Before shipping or reviewing an API, verify:

    line 246

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

Principles and patterns for designing APIs that are consistent, predictable, and easy to evolve. Applies to any language or framework — the focus is on protocol-level design decisions, not implementation details.

A well-designed API treats its surface as a product: consumers should be able to predict behavior, recover from errors, and integrate without reading source code.

When to Use

  • Designing a new public or internal API from scratch
  • Reviewing an existing API for consistency and usability
  • Choosing between REST and GraphQL for a project
  • Planning API versioning or migration strategy
  • Defining error response contracts across services
  • Establishing API standards for a team or organization

REST vs GraphQL

AspectRESTGraphQL
Best forCRUD-heavy, resource-oriented domainsComplex, interconnected data with varied client needs
Data fetchingFixed response shapes per endpointClient specifies exact fields needed
Over-fetchingCommon — endpoints return full resourcesEliminated — clients request only what they need
Under-fetchingCommon — requires multiple round tripsEliminated — single query can span relations
CachingBuilt-in HTTP caching (ETags, Cache-Control)Requires custom caching (normalized stores, persisted queries)
File uploadsNative multipart supportRequires workarounds (multipart spec or separate endpoint)
Real-timeWebhooks, SSE, or pollingSubscriptions built into the spec
Tooling maturityMature — OpenAPI, Postman, HTTP clientsGrowing — Apollo, Relay, GraphiQL
Learning curveLower — leverages existing HTTP knowledgeHigher — schema language, resolvers, query optimization
Error handlingHTTP status codes + response bodyAlways 200 — errors in response errors array
VersioningURL path, headers, or query paramsSchema evolution via deprecation + additive changes

Choose REST when: your domain maps naturally to resources and CRUD operations, you need HTTP caching, or your clients are simple (mobile apps, third-party integrations).

Choose GraphQL when: clients have highly varied data needs, you are aggregating multiple backend services, or you want a strongly typed contract between frontend and backend.

Both are valid. Many systems use REST for external/public APIs and GraphQL for internal frontend-backend communication.

REST Design Principles

REST APIs model the domain as resources and use HTTP semantics to operate on them.

Core rules:

  • Resources are nouns, not verbs: /orders, not /getOrders
  • HTTP methods are the verbs: GET reads, POST creates, PUT replaces, PATCH updates, DELETE removes
  • URLs identify resources; query parameters filter, sort, or paginate them
  • Use plural nouns for collections: /users, /users/{id}
  • Limit nesting to two levels: /users/{id}/orders is fine; /users/{id}/orders/{id}/items/{id}/variants is not
  • Use HTTP status codes meaningfully — do not return 200 for everything
  • Support content negotiation via Accept and Content-Type headers

HATEOAS (Hypermedia as the Engine of Application State) adds discoverability by including links in responses. Useful for public APIs but often overkill for internal services:

{
  "id": 42,
  "status": "shipped",
  "_links": {
    "self": { "href": "/orders/42" },
    "cancel": { "href": "/orders/42/cancel", "method": "POST" },
    "customer": { "href": "/customers/7" }
  }
}

See REST Patterns Reference for detailed conventions.

GraphQL Design Principles

GraphQL APIs expose a strongly typed schema that clients query declaratively.

Core rules:

  • Design schema-first — define the type system before writing resolvers
  • Types represent domain concepts; fields represent attributes and relations
  • Queries read data, mutations write data, subscriptions stream data
  • Use the type system to enforce constraints (non-null, enums, input types)
  • Avoid deeply nested schemas that create unpredictable query costs
  • Solve N+1 problems with batching (dataloader pattern)
  • Limit query depth and complexity to prevent abuse

Schema-first example:

type User {
  id: ID!
  name: String!
  email: String!
  orders(first: Int, after: String): OrderConnection!
}

type Order {
  id: ID!
  total: Float!
  status: OrderStatus!
  createdAt: DateTime!
}

enum OrderStatus {
  PENDING
  CONFIRMED
  SHIPPED
  DELIVERED
  CANCELLED
}

See GraphQL Patterns Reference for detailed conventions.

Error Handling

A consistent error format is one of the most impactful API design decisions. Consumers should be able to parse errors programmatically without inspecting message strings.

RFC 7807 Problem Details format (recommended for REST):

{
  "type": "https://api.example.com/errors/insufficient-funds",
  "title": "Insufficient Funds",
  "status": 422,
  "detail": "Account balance is $10.00 but the transfer requires $50.00.",
  "instance": "/transfers/abc-123",
  "errors": [
    {
      "field": "amount",
      "code": "insufficient_funds",
      "message": "Transfer amount exceeds available balance"
    }
  ]
}

Key principles:

  • Use a machine-readable type or code — clients should branch on codes, not messages
  • Include a human-readable detail for debugging
  • Return field-level errors for validation failures so clients can highlight specific inputs
  • Use appropriate HTTP status codes (REST) or structured error types (GraphQL)
  • Never expose stack traces, internal paths, or SQL queries in production
  • Include a correlation/request ID for tracing errors across services

GraphQL error conventions:

{
  "data": { "createOrder": null },
  "errors": [
    {
      "message": "Insufficient funds",
      "extensions": {
        "code": "INSUFFICIENT_FUNDS",
        "field": "amount"
      }
    }
  ]
}

Versioning

APIs evolve. Versioning strategies determine how you ship changes without breaking existing consumers.

StrategyMechanismProsCons
URL path/v1/usersExplicit, easy to routeURL pollution, hard to deprecate
Accept headerAccept: application/vnd.api+json;version=2Clean URLs, HTTP-correctLess visible, harder to test casually
Query param/users?version=2Simple to implementEasy to forget, caching complications

Practical guidance:

  • URL path versioning is the most common and easiest for consumers to understand
  • Only bump the major version for breaking changes
  • Prefer evolving the API additively (new fields, new endpoints) over creating new versions
  • When a version is deprecated, communicate a sunset date and provide migration guides

See API Evolution Reference for detailed strategies.

Pagination

Every list endpoint needs pagination. The choice between cursor and offset affects performance, consistency, and client complexity.

ApproachHow it worksProsCons
Offset?offset=20&limit=10Simple, supports "jump to page N"Inconsistent with real-time inserts/deletes, slow on large tables
Cursor?after=abc123&limit=10Stable with real-time data, performant at scaleCannot jump to arbitrary pages

Best practices:

  • Set a maximum page size (e.g., 100) and a sensible default (e.g., 20)
  • Return pagination metadata: hasNextPage, hasPreviousPage, totalCount (if cheap to compute)
  • If totalCount is expensive, make it optional or return an estimate
  • Use cursors for feeds, activity streams, and any data that changes frequently
  • Use offset for admin dashboards, reports, and datasets that rarely change during browsing

Cursor pagination response example:

{
  "data": [ ... ],
  "pagination": {
    "hasNextPage": true,
    "hasPreviousPage": false,
    "startCursor": "eyJpZCI6MX0=",
    "endCursor": "eyJpZCI6MTB9"
  }
}

Authentication & Authorization

Authentication verifies identity (who are you?). Authorization verifies permissions (what can you do?).

MechanismUse caseNotes
API keysServer-to-server, simple integrationsEasy to implement; rotate regularly; never expose in client code
OAuth 2.0Third-party access, delegated permissionsIndustry standard; use Authorization Code + PKCE for SPAs/mobile
JWT (Bearer tokens)Stateless auth for microservicesInclude only essential claims; set short expiry; validate signature and claims
Session cookiesBrowser-based web appsPair with CSRF protection; use Secure, HttpOnly, SameSite flags

Best practices:

  • Always use HTTPS — no exceptions
  • Transmit tokens in Authorization: Bearer <token> header, not in query strings
  • Implement scopes/permissions for fine-grained access control
  • Return 401 Unauthorized for missing/invalid credentials, 403 Forbidden for insufficient permissions
  • Rate-limit authentication endpoints aggressively to prevent brute-force attacks
  • Support token refresh flows to avoid forcing re-authentication

Common Antipatterns

AntipatternProblemFix
Chatty APIClients need 10+ requests to render a pageAggregate related data; consider GraphQL or composite endpoints
God endpointSingle endpoint accepts wildly different payloads via flagsSplit into focused endpoints with clear semantics
Inconsistent namingMix of snake_case, camelCase, plural/singularPick one convention and enforce it project-wide
Missing paginationList endpoints return unbounded resultsAlways paginate collections; set max page size
Breaking changes without versioningRenaming or removing fields breaks clients silentlyUse versioning or additive-only evolution
Leaking internalsDatabase column names, auto-increment IDs in URLsMap to stable external identifiers (UUIDs, slugs)
Ignoring idempotencyRetrying a POST creates duplicate resourcesSupport idempotency keys for non-idempotent operations
200 for everythingErrors return HTTP 200 with an error bodyUse appropriate HTTP status codes
Timestamps without timezone2024-01-15 14:30:00 is ambiguousAlways use ISO 8601 with timezone: 2024-01-15T14:30:00Z

Quality Checklist

Before shipping or reviewing an API, verify:

  • Resource naming is consistent (plural nouns, no verbs in URLs)
  • HTTP methods match semantics (GET is safe, PUT/DELETE are idempotent)
  • Every list endpoint is paginated with a max page size
  • Error responses use a consistent format with machine-readable codes
  • Authentication is required and uses HTTPS
  • Rate limiting is in place with appropriate headers
  • Breaking changes are versioned or avoided via additive evolution
  • Request/response examples exist for every endpoint
  • Timestamps use ISO 8601 with timezone
  • IDs are stable external identifiers, not internal auto-increments
  • CORS is configured for browser clients (if applicable)
  • Compression (gzip/brotli) is enabled for responses
  • API documentation is generated from the source of truth (OpenAPI schema, GraphQL introspection)

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.