agentleFS
nisarthnisarth/claude-skills-store/skills/engineering/api-design/SKILL.md

api-design

Skill1 starsChanged 7 months agoMITView on GitHub

Design clean, consistent REST and GraphQL APIs. Endpoint naming, versioning, pagination, error handling, authentication, rate limiting, and OpenAPI documentation. Trigger with "design an API", "API endpoint for", "REST vs GraphQL", "how should I structure my API", "API versioning", "pagination strategy", or when the user needs help designing, reviewing, or documenting APIs.

191 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use db-design, everything-claude-code and 10 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.
  • yuexueyuSkill

    db-design

    数据库工程师技能 - Schema设计、索引优化、并发安全、数据库审计。当你涉及数据库表/字段/索引/SQL/迁移/MCP数据库操作、建表改表、写查询时必须使用此技能。即使用户只是说"加个字段"或"查下数据",也应触发。

    Also in 4 projects that use this

  • InfopibeSkill

    everything-claude-code

    Also in 9 projects that use this

  • mryeastcodeSkill

    everything-claude-code-conventions

    Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

    Also in 8 projects that use this

  • tpavanipradeepSkill

    nextjs-turbopack

    Next.js 16+ and Turbopack — incremental bundling, FS caching, dev speed, and when to use Turbopack vs webpack.

    Also in 15 projects that use this

  • Indium-AI-LabsSkill

    data-pipeline-design

    Design batch or incremental ETL and ELT pipelines and warehouse models: grain, partitioning, idempotent loads, late-arriving data, data quality tests, PII controls, and cost monitoring, before building them. Use when adding or changing a dbt model, warehouse table, scheduled transformation, or ingestion job. Not for transactional schema design (use the database-design skill) or event-sourced stores (use the event-sourcing-architecture skill).

    Also in 3 projects that use this

  • thejordanleopoldSkill

    third-party-integration

    Use when integrating with external APIs, payment processors (Stripe), webhooks, or third-party services. Use when implementing API clients with authentication and rate limiting, handling webhooks with signature verification and idempotency, writing contract tests for external services, or isolating third-party dependencies behind adapters. Triggers: \"Stripe\", \"payment integration\", \"webhook\", \"third-party API\", \"external service\", \"API client\", \"integrate with\", \"signature verification\", \"idempotency key\".

    Also in 3 projects that use this

The file

Show its rules and text

We split this skill into the rules it gives an agent

20 rules. 0 are common, 12 are distinctive, and 8 are very specific to this project.

  • 0

    Common

    Most of the 165 edited versions we read keep these.

  • 12

    Distinctive

    This author's own choices. Worth a look.

  • 8

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Before designing endpoints, understand the data model and use cases:

    line 33
  2. Distinctive:

    Check existing patterns: If the project has existing APIs, read them to maintain consistency.

    line 39
  3. Distinctive:

    Look at existing code:

    line 41
  4. Distinctive:

    Read route/controller files for current endpoint patterns.

    line 42
  5. Distinctive:

    Check for API documentation (OpenAPI spec, Swagger UI, GraphQL schema).

    line 43
  6. Very specific:

    Use plural nouns for collections: /users, /orders, /products

    line 49
  7. Very specific:

    Use resource IDs for individual items: /users/{userId}

    line 50
  8. Very specific:

    Use kebab-case for multi-word resources: /order-items, /shipping-addresses

    line 53
  9. Very specific:

    Use query parameters for filtering, not path segments: /orders?status=pending

    line 54
  10. Very specific:

    Use Relay-style connections for paginated lists (edges, nodes, pageInfo).

    line 164
  11. Distinctive:

    Use input types for mutations, payload types for responses.

    line 165
  12. Distinctive:

    Use enums for finite sets of values.

    line 169
  13. Very specific:

    Use 429 Too Many Requests with Retry-After header.

    line 180
  14. Distinctive:

    Use sliding window or token bucket algorithms.

    line 182
  15. Distinctive:

    Action: Read existing routes, check naming conventions, HTTP method usage, error responses, and pagination patterns.

    line 267
  16. Distinctive:

    Use HTTP methods correctly.

    line 276
  17. Very specific:

    Always return the created/updated resource in POST/PUT/PATCH responses.

    line 277
  18. Very specific:

    Use ETag and If-None-Match for conditional requests to reduce bandwidth.

    line 280
  19. Distinctive:

    Keep endpoint count manageable.

    line 282
  20. Distinctive:

    Document every endpoint, including error responses.

    line 283

“Common” is measured: kept by at least 6 in 10 of the 165 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

Design, review, and document REST and GraphQL APIs. Covers resource naming, HTTP method selection, pagination, filtering, error responses, authentication, rate limiting, versioning, and OpenAPI/GraphQL schema generation.

Workflow

Step 1: Understand the Domain

Before designing endpoints, understand the data model and use cases:

  • Identify resources: What are the core entities? (users, orders, products, etc.)
  • Map relationships: How do resources relate? (one-to-many, many-to-many)
  • List operations: What actions do consumers need? (CRUD, search, aggregate, bulk)
  • Identify consumers: Who calls this API? (frontend, mobile, third-party, internal services)
  • Check existing patterns: If the project has existing APIs, read them to maintain consistency.

Look at existing code:

  • Read route/controller files for current endpoint patterns.
  • Check for API documentation (OpenAPI spec, Swagger UI, GraphQL schema).
  • Review middleware for auth, validation, rate limiting.

Step 2: REST API Design

Resource Naming Conventions:

  • Use plural nouns for collections: /users, /orders, /products
  • Use resource IDs for individual items: /users/{userId}
  • Nest related resources: /users/{userId}/orders
  • Limit nesting to 2 levels max: /users/{userId}/orders/{orderId}
  • Use kebab-case for multi-word resources: /order-items, /shipping-addresses
  • Use query parameters for filtering, not path segments: /orders?status=pending

HTTP Method Selection:

MethodPurposeIdempotentSafeResponse Code
GETRead a resourceYesYes200
POSTCreate a resourceNoNo201
PUTReplace a resource entirelyYesNo200
PATCHPartial updateNo*No200
DELETERemove a resourceYesNo204

Pagination (choose one pattern):

Offset-based (simple, allows page jumping):

GET /orders?page=2&per_page=20
Response headers: X-Total-Count: 142, Link: <...>; rel="next"

Cursor-based (stable, better for real-time data):

GET /orders?cursor=eyJpZCI6MTAwfQ&limit=20
Response: { "data": [...], "next_cursor": "eyJpZCI6MTIwfQ", "has_more": true }

Keyset-based (performant for large datasets):

GET /orders?after_id=100&limit=20

Filtering and Sorting:

GET /orders?status=pending&created_after=2024-01-01&sort=-created_at,+total
GET /products?category=electronics&price_min=10&price_max=100
GET /users?search=john&fields=id,name,email

Error Response Format (RFC 7807 Problem Details):

{
  "type": "https://api.example.com/errors/validation-failed",
  "title": "Validation Failed",
  "status": 422,
  "detail": "The request body contains invalid fields.",
  "instance": "/orders/create",
  "errors": [
    {
      "field": "email",
      "message": "Must be a valid email address",
      "code": "INVALID_FORMAT"
    }
  ]
}

Standard HTTP Status Codes:

  • 200 OK — Successful read or update
  • 201 Created — Successful creation (include Location header)
  • 204 No Content — Successful deletion
  • 400 Bad Request — Malformed request syntax
  • 401 Unauthorized — Missing or invalid authentication
  • 403 Forbidden — Authenticated but not authorized
  • 404 Not Found — Resource does not exist
  • 409 Conflict — State conflict (duplicate, version mismatch)
  • 422 Unprocessable Entity — Validation errors
  • 429 Too Many Requests — Rate limit exceeded (include Retry-After header)
  • 500 Internal Server Error — Unexpected server failure

Step 3: GraphQL API Design

Schema Design:

type Query {
  user(id: ID!): User
  users(filter: UserFilter, pagination: PaginationInput): UserConnection!
  order(id: ID!): Order
}

type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
  updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
  deleteUser(id: ID!): DeleteUserPayload!
}

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

input CreateUserInput {
  email: String!
  name: String!
}

type CreateUserPayload {
  user: User
  errors: [UserError!]!
}

type UserError {
  field: String
  message: String!
  code: ErrorCode!
}

GraphQL Best Practices:

  • Use Relay-style connections for paginated lists (edges, nodes, pageInfo).
  • Use input types for mutations, payload types for responses.
  • Return errors in the payload, not as GraphQL errors (reserve those for system failures).
  • Implement DataLoader for N+1 prevention.
  • Set query depth and complexity limits to prevent abuse.
  • Use enums for finite sets of values.

Step 4: Authentication and Rate Limiting

Authentication patterns:

  • API Keys: Simple, best for server-to-server. Send in Authorization: Bearer <key> or X-API-Key header.
  • JWT: Stateless, best for user sessions. Short-lived access tokens + refresh tokens.
  • OAuth 2.0: Best for third-party integrations. Use authorization code flow with PKCE for public clients.

Rate Limiting:

  • Return rate limit info in headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset.
  • Use 429 Too Many Requests with Retry-After header.
  • Apply different limits per endpoint sensitivity (login stricter than read).
  • Use sliding window or token bucket algorithms.

Step 5: Versioning Strategy

  • URL path versioning: /v1/users, /v2/users — most common, clear, easy to route.
  • Header versioning: Accept: application/vnd.api+json; version=2 — cleaner URLs, harder to test.
  • Query parameter: /users?version=2 — easy to test, pollutes query string.

Recommended approach: URL path versioning with a deprecation policy.

Step 6: Documentation

Generate OpenAPI 3.0 specification:

openapi: 3.0.3
info:
  title: <API Name>
  version: 1.0.0
  description: <description>
paths:
  /users:
    get:
      summary: List users
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'

Output Format

## API Design

### Resources
| Resource | Endpoints | Description |
|----------|-----------|-------------|
| <name> | <count> | <purpose> |

### Endpoints

#### <METHOD> <path>
**Purpose**: <what it does>
**Auth**: <required | optional | public>
**Request**:
```json
<example request body>

Response (200):

<example response body>

Errors: <list of possible error codes>

Authentication

<strategy and implementation details>

Pagination

<chosen strategy with examples>

Rate Limiting

<limits per tier/endpoint>

Versioning

<strategy and deprecation policy> ```

Examples

User: "Design a REST API for an e-commerce platform" Action: Identify resources (users, products, orders, cart), design endpoints for each, define pagination, error format, auth strategy, and produce an OpenAPI spec.

User: "Should I use REST or GraphQL for my mobile app?" Action: Compare both approaches considering mobile-specific needs (bandwidth, flexibility, caching), recommend based on the use case.

User: "Review my API endpoints for consistency" Action: Read existing routes, check naming conventions, HTTP method usage, error responses, and pagination patterns. Report inconsistencies with fixes.

User: "Add pagination to my list endpoints" Action: Assess the data characteristics, recommend cursor vs offset pagination, provide implementation code and response format.

Best Practices

  • Be consistent. If one endpoint uses snake_case, all endpoints should. If one returns errors in a certain format, all should.
  • Design for the consumer, not the database. API resources do not need to mirror database tables.
  • Use HTTP methods correctly. GET should never have side effects. DELETE should be idempotent.
  • Always return the created/updated resource in POST/PUT/PATCH responses. Saves the client a round trip.
  • Version from day one. Adding versioning later is painful.
  • Provide _links or Link headers for discoverability (HATEOAS) on public APIs.
  • Use ETag and If-None-Match for conditional requests to reduce bandwidth.
  • Design idempotency into write operations using Idempotency-Key headers for payment or order APIs.
  • Keep endpoint count manageable. If you have 200 endpoints, you likely need to rethink your resource model.
  • Document every endpoint, including error responses. Consumers cannot use what they cannot understand.

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.