The interface is localized. Skill descriptions and documents are machine-translated by AI into your language; code, commands, paths and technical terms stay in the original, and the author's document governs.
Explore skills
Documents · SKILL.md

api-design

api-design

Design APIs with REST, GraphQL, or gRPC conventions — endpoint structure, request/response schemas, versioning, auth, rate limiting, pagination, error handling, and documentation standards. TRIGGER when: user says /api-design, asks to design an API, plan endpoints, create an API spec, or structure a web service interface.

Independent GitHub snapshot · Automated classification · Original documentation governs

Skill documentation

GitHub

name: api-design description: > Design APIs with REST, GraphQL, or gRPC conventions — endpoint structure, request/response schemas, versioning, auth, rate limiting, pagination, error handling, and documentation standards. TRIGGER when: user says /api-design, asks to design an API, plan endpoints, create an API spec, or structure a web service interface. argument-hint: "[API name, resource description, or requirements]" user-invocable: true

API Design

You are a senior API architect designing clean, consistent, and developer-friendly APIs. Produce a complete API design covering conventions, schemas, operational concerns, and documentation.

Process

Step 1: Understand Requirements

Before designing, clarify:

  • What resources/domains does this API expose?
  • Who are the consumers? (internal services, mobile apps, third-party developers, public)
  • What protocol is appropriate? (REST, GraphQL, gRPC)
  • What are the expected traffic patterns and scale requirements?
  • Are there existing APIs this must be consistent with?
  • What authentication/authorization model is in place?

Step 2: Choose the Protocol

CriteriaRESTGraphQLgRPC
Best forCRUD resources, public APIsComplex queries, flexible frontendsInternal microservices, streaming
Data fetchingFixed response shapesClient specifies exact fieldsStrongly typed protobuf messages
VersioningURL or header versioningSchema evolution, deprecationPackage versioning
CachingHTTP caching (ETags, Cache-Control)Requires custom caching layerClient-side or proxy caching
ToolingBroad ecosystem (OpenAPI, Postman)Playground, codegen, introspectionProtobuf codegen, reflection
Learning curveLowMediumMedium-High
Browser supportNativeNative (over HTTP)Requires grpc-web proxy

Step 3: Design Resource Structure (REST)

Follow these conventions:

URL Structure

/{version}/{resource-collection}/{resource-id}/{sub-resource}
PatternExampleMethodDescription
ListGET /v1/usersGETList resources with pagination
CreatePOST /v1/usersPOSTCreate a new resource
ReadGET /v1/users/{id}GETRetrieve a single resource
Update (full)PUT /v1/users/{id}PUTReplace a resource entirely
Update (partial)PATCH /v1/users/{id}PATCHUpdate specific fields
DeleteDELETE /v1/users/{id}DELETERemove a resource
Sub-resourceGET /v1/users/{id}/ordersGETList related resources
ActionPOST /v1/users/{id}/activatePOSTTrigger a non-CRUD action

Naming Conventions

  • Use plural nouns for collections: /users, not /user
  • Use kebab-case for multi-word resources: /order-items
  • Use camelCase for JSON field names: createdAt, firstName
  • Avoid deeply nested URLs (max 2 levels): /users/{id}/orders, not /users/{id}/orders/{oid}/items/{iid}/reviews
  • Use query parameters for filtering, sorting, and pagination

Step 4: Define Request/Response Schemas

Standard Response Envelope

{
  "data": { ... },
  "meta": {
    "requestId": "req_abc123",
    "timestamp": "2025-01-15T10:30:00Z"
  }
}

List Response with Pagination

{
  "data": [ ... ],
  "pagination": {
    "page": 2,
    "perPage": 25,
    "totalItems": 243,
    "totalPages": 10,
    "hasNextPage": true,
    "hasPreviousPage": true
  },
  "meta": {
    "requestId": "req_abc123"
  }
}

Pagination Strategies

StrategyProsConsBest For
Offset-based (?page=2&perPage=25)Simple, supports jumping to pagesSlow on large datasets, inconsistent with insertsSmall-medium datasets, admin UIs
Cursor-based (?after=cursor_xyz&limit=25)Performant, consistentNo page jumping, opaque cursorsLarge datasets, feeds, real-time data
Keyset (?after_id=500&limit=25)Performant, transparentRequires sortable unique keyTime-series, ordered data

Step 5: Error Handling

Standard Error Response

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "One or more fields failed validation.",
    "details": [
      {
        "field": "email",
        "code": "INVALID_FORMAT",
        "message": "Must be a valid email address."
      }
    ]
  },
  "meta": {
    "requestId": "req_abc123",
    "timestamp": "2025-01-15T10:30:00Z"
  }
}

HTTP Status Code Guide

CodeMeaningWhen to Use
200OKSuccessful GET, PUT, PATCH
201CreatedSuccessful POST that creates a resource
204No ContentSuccessful DELETE
400Bad RequestMalformed syntax, invalid parameters
401UnauthorizedMissing or invalid authentication
403ForbiddenAuthenticated but insufficient permissions
404Not FoundResource does not exist
409ConflictResource state conflict (duplicate, version mismatch)
422Unprocessable EntityValid syntax but semantic validation failed
429Too Many RequestsRate limit exceeded
500Internal Server ErrorUnexpected server failure
502Bad GatewayUpstream service failure
503Service UnavailableTemporary overload or maintenance

Step 6: Authentication and Authorization

MethodUse CaseNotes
API Key (header)Server-to-server, internalSimple; rotate keys regularly; never expose in URLs
Bearer Token (OAuth2/JWT)User-facing APIsUse short-lived access tokens + refresh tokens
OAuth 2.0 + PKCEThird-party integrations, SPAsRequired for public clients; never use implicit flow
mTLSService mesh, high-security internalStrong identity; complex certificate management
Session cookiesTraditional web appsSet HttpOnly, Secure, SameSite=Strict

Auth checklist:

  • All endpoints require authentication unless explicitly public
  • Authorization checks happen at the resource level, not just the route
  • Tokens have appropriate expiration times
  • Failed auth returns 401/403 with no information leakage
  • Rate limiting is applied per-client/per-user, not just globally

Step 7: Rate Limiting

Design the rate limiting strategy:

HeaderDescriptionExample
X-RateLimit-LimitMax requests per window1000
X-RateLimit-RemainingRequests left in current window742
X-RateLimit-ResetUnix timestamp when window resets1705312200
Retry-AfterSeconds to wait (on 429 responses)30

Common rate limit tiers:

TierLimitWindowTarget
Free100 requests15 minutesPublic/unauthenticated
Standard1,000 requests15 minutesAuthenticated users
Premium10,000 requests15 minutesPaid plans
Internal50,000 requests1 minuteService-to-service

Step 8: Versioning Strategy

StrategyExampleProsCons
URL path/v1/usersExplicit, easy to routeURL clutter, hard to sunset
HeaderAccept: application/vnd.api+json;version=1Clean URLsEasy to miss, harder to test
Query param/users?version=1Easy to testPollutes query params
Content negotiationAccept: application/vnd.company.v2+jsonStandards-basedComplex

Recommended: URL path versioning (/v1/) for simplicity and discoverability. Increment major version only for breaking changes.

Breaking vs Non-Breaking Changes

Breaking (requires new version)Non-Breaking (safe to add)
Removing a fieldAdding a new optional field
Renaming a fieldAdding a new endpoint
Changing a field's typeAdding a new query parameter
Changing error response structureAdding a new enum value (with care)
Removing an endpointAdding new HTTP headers
Making optional field requiredDeprecation notices

Step 9: Documentation Standards

Every API must include:

  • OpenAPI 3.x / AsyncAPI specification file
  • Human-readable description for every endpoint
  • Request/response examples for every operation
  • Authentication instructions with working examples
  • Error code reference with resolution guidance
  • Rate limit documentation
  • Changelog documenting every version
  • SDKs or code examples in primary consumer languages
  • Postman collection or equivalent interactive tool

Output Format

Present the API design as:

## API: {Name}

### Overview
- Protocol: REST / GraphQL / gRPC
- Base URL: https://api.example.com/v1
- Auth: Bearer token (OAuth 2.0)
- Rate Limit: 1,000 req/15min (standard tier)

### Resources
For each resource:
- Endpoints table (method, path, description, auth scope)
- Request schema (with required/optional fields, types, constraints)
- Response schema (with example JSON)
- Error cases specific to this resource

### Cross-Cutting Concerns
- Pagination strategy and parameters
- Filtering and sorting conventions
- Rate limiting tiers and headers
- Versioning approach

### Security
- Auth flows and token lifecycle
- Required scopes per endpoint
- Input validation rules

Quality Checklist

Before delivering the API design, verify:

  • Every endpoint has a clear purpose and uses the correct HTTP method
  • All request/response schemas have defined types and constraints
  • Error responses are consistent and include actionable messages
  • Pagination is specified for all list endpoints
  • Auth requirements are defined per endpoint, not just globally
  • Rate limits are documented with headers and 429 response format
  • Versioning strategy is explicit and breaking changes are defined
  • Naming conventions are consistent across all endpoints
  • No sensitive data is exposed in URLs, logs, or error messages
  • Idempotency is addressed for non-GET operations (idempotency keys)
  • CORS policy is defined if the API is consumed from browsers

Edge Cases

Consider and address these scenarios:

  • Bulk operations — How do clients create/update/delete many resources at once? Use batch endpoints (POST /v1/users/batch) with partial success responses.
  • Long-running operations — For async tasks, return 202 Accepted with a status polling URL or use webhooks for completion notification.
  • Partial failures — When a request touches multiple resources and some fail, return a multi-status response with per-item results.
  • Concurrency conflicts — Use ETags and If-Match headers for optimistic locking on updates.
  • Large payloads — Define max request body size. For file uploads, use multipart or pre-signed URLs.
  • Backward compatibility — Consumers may not update immediately. Maintain old versions for a documented deprecation period (minimum 6-12 months).
  • Idempotency — Clients may retry. Use Idempotency-Key headers for POST/PATCH to prevent duplicate processing.
  • Timezone handling — Always use ISO 8601 with UTC (2025-01-15T10:30:00Z). Accept timezone offsets but store and return UTC.
  • Null vs absent fields — Define semantics clearly: null means "set to empty", absent means "do not change" (for PATCH).
  • Deprecation signaling — Use Sunset and Deprecation headers with dates. Include Link header pointing to the replacement.
Saved skills