api-design

v2026.09.24

Use when designing API endpoints, defining request/response schemas, generating OpenAPI specifications, choosing between REST/GraphQL/tRPC, or establishing API conventions for a project

GitHub
Install command
npx skhub add pixel-process-ug/api-design
Markdown
SKILL.md

API Design

Overview

Structured API endpoint design through guided discovery. Produces consistent, well-documented API designs with OpenAPI/Swagger specifications. Covers resource modeling, authentication, pagination, error handling, and versioning — ensuring consumer-centric design before any implementation begins.

Announce at start: "I'm using the api-design skill to design the API."

Phase 1: Discovery

Ask these questions ONE AT A TIME:

Resource Questions

#QuestionWhat It Determines
1What entities/resources does this API manage?Resource naming
2What are the relationships between them?Nested routes, includes
3What operations are needed for each? (CRUD, search, batch)HTTP methods, endpoints

Consumer Questions

#QuestionWhat It Determines
4Who will consume this API? (frontend, mobile, third-party, internal)Response shape, auth model
5What authentication/authorization is needed?Security scheme
6What rate limits or quotas apply?Rate limiting headers

Constraint Questions

#QuestionWhat It Determines
7REST, GraphQL, or tRPC?API paradigm
8Versioning strategy? (URL path, header, query param)URL structure
9Pagination approach? (cursor, offset, keyset)List response shape
10Existing API conventions in the codebase?Consistency constraints

API Paradigm Decision Table

FactorChoose RESTChoose GraphQLChoose tRPC
ConsumersMultiple, diverseFrontend-heavy, flexible queriesTypeScript monorepo
Caching needsStrong (HTTP caching)Moderate (client-side)Low (internal only)
Data shapePredictable, resource-orientedNested, variable-shapeType-safe RPC
Team familiarityUniversalRequires schema knowledgeRequires TypeScript
Real-time needsWebSocket addonSubscriptions built-inSubscription support

STOP after discovery — present a summary of resources, operations, and constraints. Get confirmation before designing endpoints.

Phase 2: Design Endpoints

For each endpoint, define:

### [METHOD] /api/v1/[resource]

**Purpose:** [what this endpoint does]

**Request:**
- Headers: `Authorization: Bearer <token>`
- Query params: `?page=1&limit=20&sort=created_at:desc`
- Body:
  ```json
  {
    "field": "type — description"
  }

Response (200):

{
  "data": [...],
  "meta": { "total": 100, "page": 1, "limit": 20 }
}

Error Responses:

StatusCodeDescription
400VALIDATION_ERRORInvalid request body
401UNAUTHORIZEDMissing or invalid token
404NOT_FOUNDResource doesn't exist
409CONFLICTResource already exists

Authorization: [who can access this]


### HTTP Method Decision Table

| Operation | Method | Status (success) | Idempotent |
|-----------|--------|-----------------|------------|
| List resources | GET | 200 | Yes |
| Get single resource | GET | 200 | Yes |
| Create resource | POST | 201 | No |
| Full replace | PUT | 200 | Yes |
| Partial update | PATCH | 200 | No |
| Delete resource | DELETE | 204 | Yes |
| Bulk create | POST | 201 | No |
| Search (complex) | POST | 200 | Yes (safe) |

### Pagination Decision Table

| Approach | When to Use | Pros | Cons |
|----------|------------|------|------|
| **Cursor** | Real-time feeds, large datasets | Consistent, no skipping | Cannot jump to page N |
| **Offset** | Small datasets, admin panels | Simple, jumpable | Skips/duplicates on insert |
| **Keyset** | Time-series, logs | Efficient on large tables | Requires sortable key |

### Error Response Format

All endpoints must use a consistent error shape:

```json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Human-readable description",
    "details": [
      { "field": "email", "message": "Invalid email format" }
    ]
  }
}

Status Code Reference

CodeMeaningWhen to Use
200OKSuccessful GET, PUT, PATCH
201CreatedSuccessful POST that creates
204No ContentSuccessful DELETE
400Bad RequestValidation failure
401UnauthorizedMissing or invalid credentials
403ForbiddenValid credentials, insufficient permissions
404Not FoundResource does not exist
409ConflictDuplicate or state conflict
422Unprocessable EntityValid JSON but semantic error
429Too Many RequestsRate limit exceeded
500Internal Server ErrorUnexpected server failure

STOP after endpoint design — present each endpoint for review and approval.

Phase 3: Generate OpenAPI Spec

openapi: 3.1.0
info:
  title: [API Name]
  version: 1.0.0
  description: [API description]

servers:
  - url: http://localhost:3000/api/v1
    description: Development
  - url: https://api.example.com/v1
    description: Production

paths:
  /resource:
    get:
      summary: List resources
      parameters: [...]
      responses: [...]
    post:
      summary: Create resource
      requestBody: [...]
      responses: [...]

components:
  schemas: [...]
  securitySchemes: [...]

STOP after spec generation — validate the YAML and present for final approval.

Phase 4: Save and Transition

After explicit approval:

  1. Save OpenAPI spec to docs/api/YYYY-MM-DD-<api-name>.yaml
  2. Commit with message: docs(api): add OpenAPI spec for <api-name>
  3. Determine next step based on user intent

Transition Decision Table

User IntentNext SkillRationale
"Let's implement this"planningCreate implementation plan from API spec
"Write specs for this"spec-writingBehavioral specs for each endpoint
"Generate client SDK"ManualUse OpenAPI codegen tools
"Just save the design"NoneAPI design is the deliverable
"Add tests"testing-strategyDefine API test approach

Design Principles

PrincipleRule
Consistent namingPlural nouns for collections (/users, not /user)
Proper HTTP methodsGET reads, POST creates, PUT replaces, PATCH updates, DELETE removes
Proper status codesUse the right code for the right situation (see table above)
Consistent error formatSame error shape across all endpoints
Pagination by defaultAll list endpoints paginated
Filtering and sortingQuery params for list endpoints
IdempotencyPUT and DELETE are always idempotent
HATEOASInclude links for discoverability (when appropriate)

Anti-Patterns / Common Mistakes

MistakeWhy It Is WrongWhat To Do Instead
Verb-based URLs (/getUsers)Not RESTful, breaks conventionsUse nouns: GET /users
Inconsistent plural/singularConfuses consumersAlways plural for collections
Returning 200 for errorsHides failures from clientsUse proper status codes
No pagination on list endpointsPerformance bomb on large datasetsAlways paginate
Different error formats per endpointClients can't build generic error handlingOne error shape for all
Exposing internal IDs in URLsSecurity and coupling riskUse UUIDs or slugs
No versioning strategyBreaking changes break clientsVersion from day one
Designing without knowing consumersAPI serves no one wellDiscovery phase first

Anti-Rationalization Guards

  • Do NOT skip the discovery phase — understand consumers and constraints first
  • Do NOT design endpoints without defining error responses
  • Do NOT skip pagination for any list endpoint
  • Do NOT use inconsistent naming across endpoints
  • Do NOT generate the OpenAPI spec without user approval of endpoint designs
  • Do NOT mix API paradigms (REST + GraphQL) without explicit justification

Integration Points

SkillRelationship
spec-writingDownstream: API design informs behavioral specifications
planningDownstream: API endpoints become implementation tasks
tech-docs-generatorDownstream: OpenAPI spec feeds API reference docs
testing-strategyDownstream: API design informs integration test strategy
security-reviewDownstream: auth/authz model reviewed for vulnerabilities
database-schema-designUpstream: data model informs resource design
prd-generationUpstream: PRD requirements drive API resource identification

Verification Gate

Before claiming the API design is complete:

  1. VERIFY all endpoints have request/response schemas
  2. VERIFY all error responses are documented with consistent format
  3. VERIFY authentication is specified for each endpoint
  4. VERIFY pagination is defined for all list endpoints
  5. VERIFY the OpenAPI spec is valid YAML
  6. VERIFY user has approved each endpoint individually

Skill Type

Flexible — Adapt API paradigm, pagination style, and auth model to project needs while preserving the discovery-first approach, consistent error handling, and consumer-centric design principles.

Discovery
Tags

No tags published for this skill.

Version
Latest version metadata

Version

v2026.09.24

Published

Sep 24, 2026

Category

Uncategorized

License

MIT

Source path

templates/skills/api-design

Default branch

main

Latest commit

cc7fcb7

Tree SHA

7a49a40