Skip to content
api-design-patterns logo

API Design Patterns

api-design-patterns

Design robust APIs with RESTful patterns, GraphQL schemas, versioning strategies, and error handling conventions. Supports OpenAPI/Swagger documentation and SDK generation patterns. Triggers on API design, schema definition, endpoint architecture, or developer experience requests.

SKILL.md

Full skill instructions

API Design Patterns

Build APIs that developers love to use.

Design Principles

The Three Laws of API Design

  1. Predictable: Consistent patterns throughout
  2. Discoverable: Self-documenting, intuitive naming
  3. Evolvable: Can change without breaking clients

API-First Mindset

Design → Document → Mock → Build → Test → Deploy

NOT: Build → Document (maybe) → Hope it works

REST Patterns

Resource Naming

# Collection
GET    /​users              # List users
POST   /​users              # Create user

# Item
GET    /​users/​{id}         # Get user
PUT    /​users/​{id}         # Replace user
PATCH  /​users/​{id}         # Update user
DELETE /​users/​{id}         # Delete user

# Nested resources
GET    /​users/​{id}/​posts   # User's posts
POST   /​users/​{id}/​posts   # Create post for user

# Actions (when CRUD doesn't fit)
POST   /​users/​{id}/​activate
POST   /​orders/​{id}/​cancel

Naming Conventions

DoDon't
/​users/​getUsers, /​user-list
/​users/​{id}/​users/​get/​{id}
/​users/​{id}/​posts/​getUserPosts
Plural nounsVerbs in URLs
Lowercase, hyphenscamelCase, underscores

HTTP Methods

MethodPurposeIdempotentSafe
GETReadYesYes
POSTCreateNoNo
PUTReplaceYesNo
PATCHUpdateNo*No
DELETERemoveYesNo

*PATCH can be idempotent if designed carefully

Status Codes

CodeMeaningUse When
200OKSuccessful GET, PUT, PATCH
201CreatedSuccessful POST with new resource
204No ContentSuccessful DELETE
400Bad RequestInvalid input
401UnauthorizedMissing/​invalid auth
403ForbiddenValid auth, no permission
404Not FoundResource doesn't exist
409ConflictDuplicate, state conflict
422UnprocessableValid syntax, invalid semantics
429Too Many RequestsRate limited
500Server ErrorUnhandled server error

Request/​Response Patterns

Request Body

{
  "email": "[email protected]",
  "name": "John Doe",
  "preferences": {
    "newsletter": true
  }
}

Response: Single Resource

{
  "data": {
    "id": "usr_123",
    "type": "user",
    "attributes": {
      "email": "[email protected]",
      "name": "John Doe",
      "createdAt": "2024-01-15T10:30:00Z"
    },
    "relationships": {
      "organization": {
        "id": "org_456",
        "type": "organization"
      }
    }
  }
}

Response: Collection

{
  "data": [
    { "id": "usr_123", "type": "user", ... },
    { "id": "usr_124", "type": "user", ... }
  ],
  "meta": {
    "total": 150,
    "page": 1,
    "perPage": 20
  },
  "links": {
    "self": "/​users?page=1",
    "next": "/​users?page=2",
    "last": "/​users?page=8"
  }
}

Error Response

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "details": [
      {
        "field": "email",
        "code": "INVALID_FORMAT",
        "message": "Must be a valid email address"
      }
    ],
    "requestId": "req_abc123"
  }
}

Pagination Patterns

Offset-Based

GET /​users?page=2&perPage=20
GET /​users?offset=20&limit=20

Pros: Simple, familiar Cons: Inconsistent with real-time data, slow on large datasets

Cursor-Based

GET /​users?cursor=eyJpZCI6MTIzfQ&limit=20

Response:

{
  "data": [...],
  "cursors": {
    "before": "eyJpZCI6MTAzfQ",
    "after": "eyJpZCI6MTIzfQ"
  },
  "hasMore": true
}

Pros: Consistent, performant Cons: Can't jump to page N

Keyset-Based

GET /​users?after_id=123&limit=20

Pros: Very performant Cons: Requires sortable unique field


Filtering, Sorting, Search

Filtering

# Simple
GET /​users?status=active

# Multiple values
GET /​users?status=active,pending

# Operators
GET /​users?created_at[gte]=2024-01-01
GET /​users?name[contains]=john

# Nested
GET /​users?organization.name=Acme

Sorting

# Single field
GET /​users?sort=createdAt

# Descending
GET /​users?sort=-createdAt

# Multiple fields
GET /​users?sort=-createdAt,name

Field Selection

GET /​users?fields=id,name,email
GET /​users?fields[user]=id,name&fields[posts]=title

Search

GET /​users?q=john
GET /​users?search=john+doe

Versioning Strategies

URL Path (Recommended for major versions)

GET /​v1/​users
GET /​v2/​users

Pros: Explicit, cacheable Cons: URL pollution

Header

GET /​users
Accept: application/​vnd.api+json; version=2

Pros: Clean URLs Cons: Harder to test, less visible

Query Parameter

GET /​users?version=2

Pros: Easy to test Cons: Breaks caching, URL pollution

Deprecation Pattern

Deprecation: true
Sunset: Sat, 31 Dec 2024 23:59:59 GMT
Link: </​v2/​users>; rel="successor-version"

Authentication Patterns

API Keys

# Header
Authorization: Api-Key sk_live_abc123

# Query (avoid - logged in URLs)
GET /​users?api_key=sk_live_abc123 <!-- allow-secret -->

Bearer Tokens (OAuth2/​JWT)

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Signing Requests (AWS-style)

Authorization: HMAC-SHA256 Credential=key/​date/​region/​service,
               SignedHeaders=host;x-date,
               Signature=abc123

Rate Limiting

Headers

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640000000
Retry-After: 60

Response (429)

{
  "error": {
    "code": "RATE_LIMITED",
    "message": "Rate limit exceeded",
    "retryAfter": 60
  }
}

Strategies

StrategyDescriptionUse Case
Fixed WindowX requests per minuteSimple limiting
Sliding WindowRolling time windowSmoother limiting
Token BucketBurst allowanceTraffic spikes
Leaky BucketConstant rateSteady throughput

GraphQL Patterns

Schema Design

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

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
}

type PostConnection {
  edges: [PostEdge!]!
  pageInfo: PageInfo!
}

type Query {
  user(id: ID!): User
  users(filter: UserFilter, first: Int, after: String): UserConnection!
}

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

Naming Conventions

ElementConventionExample
TypesPascalCaseUser, BlogPost
FieldscamelCasefirstName, createdAt
ArgumentscamelCaseuserId, first
EnumsSCREAMING_SNAKEUSER_STATUS, ACTIVE
MutationsverbNouncreateUser, updatePost

Error Handling

{
  "data": null,
  "errors": [
    {
      "message": "User not found",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["user"],
      "extensions": {
        "code": "NOT_FOUND",
        "timestamp": "2024-01-15T10:30:00Z"
      }
    }
  ]
}

OpenAPI Documentation

Basic Structure

openapi: 3.0.3
info:
  title: My API
  version: 1.0.0
  description: API description

servers:
  - url: https://api.example.com/​v1
    description: Production

paths:
  /​users:
    get:
      summary: List users
      operationId: listUsers
      tags: [Users]
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
      responses:
        '200':
          description: Successful response
          content:
            application/​json:
              schema:
                $ref: '#/​components/​schemas/​UserList'

components:
  schemas:
    User:
      type: object
      required: [id, email]
      properties:
        id:
          type: string
          format: uuid
        email:
          type: string
          format: email


Related Skills

Complementary Skills (Use Together)

Alternative Skills (Similar Purpose)

  • mcp-builder - If building MCP servers instead of REST/​GraphQL APIs

Prerequisite Skills (Learn First)

  • None required - this is a foundational design skill

References

  • references/​openapi-template.md - Full OpenAPI template
  • references/​error-codes.md - Standard error code catalog
  • references/​sdk-patterns.md - Client SDK design patterns

More skills from diegosouzapw

accessibility logo
diegosouzapw/awesome-omni-skill

accessibility

Accessibility guidelines for VS Code features — covers accessibility help dialogs, accessible views, verbosity settings, accessibility signals, ARIA alerts/status announcements, keyboard navigation, and ARIA labels/roles. Applies to both new interactive UI surfaces and updates to existing feature...

62 1
View
mermaid-diagrams logo
diegosouzapw/awesome-omni-skill

mermaid-diagrams

Mermaid diagram creation for flowcharts, sequences, ERDs, and more. Generate diagrams from text in markdown files. Use for documentation, architecture diagrams, and visual representations. Triggers on mermaid, flowchart, sequence diagram, ERD, entity relationship, gantt chart, pie chart, class di...

62 1
View
tauri2-react-rust logo
diegosouzapw/awesome-omni-skill

tauri2-react-rust

Guides development of cross-platform desktop apps with Tauri 2, TypeScript, React, and Rust. Use when building Tauri apps, implementing IPC, designing Rust backend or TypeScript/React frontend, when researching or cloning a website (open site, snapshot elements), when verifying local dev or built...

62 1
View
fp-ts-errors logo
diegosouzapw/awesome-omni-skill

fp-ts-errors

Handle errors as values using fp-ts Either and TaskEither for cleaner, more predictable TypeScript code. Use when implementing error handling patterns with fp-ts.

62 0
View
ring:pre-dev-research logo
diegosouzapw/awesome-omni-skill

ring:pre-dev-research

Gate 0 research phase for pre-dev workflow. Dispatches 3 parallel research agents to gather codebase patterns, external best practices, and framework documentation BEFORE creating PRD/TRD. Outputs research.md with file:line references.

62 0
View
create-assistant logo
diegosouzapw/awesome-omni-skill

create-assistant

Create and configure Vapi voice AI assistants with models, voices, transcribers, tools, hooks, and advanced settings. Use when building voice agents, phone bots, customer support assistants, or any conversational AI that handles phone or web calls.

62 0
View
codex-headless logo
diegosouzapw/awesome-omni-skill

codex-headless

Delegiere Aufgaben an OpenAI Codex CLI im Headless-Mode. Nutzt ChatGPT Subscription (KEIN API Key). Nur Workspace-Zugriff, KEIN System-Zugriff. Auto-Accept mit --full-auto. Web-Recherche mit --search.

62 0
View
social-media-scheduler logo
diegosouzapw/awesome-omni-skill

social-media-scheduler

Generate a full week of social media content for any topic. Outputs platform-optimized posts for Twitter/X, LinkedIn, and Instagram with hashtags and posting times.

62 0
View
Data Privacy Compliance logo
diegosouzapw/awesome-omni-skill

Data Privacy Compliance

Data privacy and regulatory compliance specialist for GDPR, CCPA, HIPAA, and international data protection laws. Use when implementing privacy controls, conducting data protection impact assessments, ensuring regulatory compliance, or managing data subject rights. Expert in consent management, da...

62 0
View
triple-review logo
diegosouzapw/awesome-omni-skill

triple-review

Reviews a task using the TRIPLE protocol, as the review agent.

62 0
View
Tech Stack & Architecture Decision logo
diegosouzapw/awesome-omni-skill

Tech Stack & Architecture Decision

Define and document the technology stack and architecture decisions for a project. Use when the user needs to choose a tech stack, make architecture decisions, define infrastructure choices, or document technology selections. Triggers on requests like "define the tech stack", "choose technologies...

62 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View