api-design-patterns

bobmatnyc/claude-mpm-skills · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill api-design-patterns
0 commentsdiscussion
summary

Design robust, scalable APIs using proven patterns for REST, GraphQL, and gRPC with proper versioning, authentication, and error handling.

skill.md

API Design Patterns

Design robust, scalable APIs using proven patterns for REST, GraphQL, and gRPC with proper versioning, authentication, and error handling.

Quick Reference

API Style Selection:

  • REST: Resource-based CRUD, simple clients, HTTP-native caching
  • GraphQL: Client-driven queries, complex data graphs, real-time subscriptions
  • gRPC: High-performance RPC, microservices, strong typing, streaming

Critical Patterns:

  • Versioning: URI (/v1/users), header (Accept: application/vnd.api+json;version=1), content negotiation
  • Pagination: Offset (simple), cursor (stable), keyset (performant)
  • Auth: OAuth2 (delegated), JWT (stateless), API keys (service-to-service)
  • Rate limiting: Token bucket, fixed window, sliding window
  • Idempotency: Idempotency keys, conditional requests, safe retry

See references/ for deep dives: rest-patterns.md, graphql-patterns.md, grpc-patterns.md, versioning-strategies.md, authentication.md

Core Principles

Universal API Design Standards

Apply these principles across all API styles:

1. Consistency Over Cleverness

  • Follow established conventions for your API style
  • Use predictable naming patterns (snake_case or camelCase, pick one)
  • Maintain consistent error response formats
  • Version breaking changes, never surprise clients

2. Design for Evolution

  • Plan for versioning from day one
  • Use optional fields with sensible defaults
  • Deprecate gracefully with sunset dates
  • Document breaking vs non-breaking changes

3. Security by Default

  • Require authentication unless explicitly public
  • Use HTTPS/TLS for all production endpoints
  • Implement rate limiting and throttling
  • Validate and sanitize all inputs
  • Return minimal error details to clients

4. Developer Experience First

  • Provide comprehensive documentation (OpenAPI, GraphQL schema)
  • Return meaningful error messages with actionable guidance
  • Use standard HTTP status codes correctly
  • Include request IDs for debugging
  • Offer SDKs and code generators

API Style Decision Tree

When to Choose REST

Use REST when:

  • Building CRUD-focused resource APIs
  • Clients need HTTP caching (ETags, Cache-Control)
  • Wide platform compatibility required (browsers, mobile, IoT)
  • Simple, stateless client-server model fits
  • Team familiar with HTTP/REST conventions

Avoid REST when:

  • Complex data fetching with nested relationships (N+1 queries)
  • Real-time updates are primary use case
  • Need strong typing and code generation
  • High-performance RPC between microservices

Example Use Cases: Public APIs, mobile backends, traditional web services

When to Choose GraphQL

Use GraphQL when:

  • Clients need flexible, client-driven queries
  • Complex data graphs with nested relationships
  • Multiple client types with different data needs
  • Real-time subscriptions required
  • Strong typing and schema validation needed

Avoid GraphQL when:

  • Simple CRUD operations dominate
  • HTTP caching is critical (GraphQL uses POST)
  • File uploads are primary feature (requires extensions)
  • Team lacks GraphQL expertise
  • Performance optimization is complex (N+1 problem)

Example Use Cases: Client-facing APIs, dashboards, mobile apps with varied UIs

When to Choose gRPC

Use gRPC when:

  • Microservice-to-microservice communication
  • High performance and low latency critical
  • Bidirectional streaming needed
  • Strong typing with Protocol Buffers
  • Polyglot environments (language interop)

Avoid gRPC when:

  • Browser clients (limited support, needs grpc-web)
  • HTTP/JSON required for compatibility
  • Human-readable payloads preferred
  • Simple request/response patterns

Example Use Cases: Internal microservices, streaming data, service mesh

REST API Patterns

Resource Naming

Good: Plural nouns, hierarchical

GET    /users              # List users
GET    /users/123          # Get user
POST   /users              # Create user
PUT    /users/123          # Update user (full)
PATCH  /users/123          # Update user (partial)
DELETE /users/123          # Delete user
GET    /users/123/orders   # User's orders (sub-resource)

Bad: Verbs, mixed conventions

GET    /getUsers           # Don't use verbs
POST   /user/create        # Don't use verbs
GET    /Users/123          # Don't capitalize
GET    /user/123           # Don't mix singular/plural

HTTP Status Codes

Success Codes:

  • 200 OK: Successful GET, PUT, PATCH, DELETE with body
  • 201 Created: Successful POST, return Location header
  • 202 Accepted: Async operation started
  • 204 No Content: Successful DELETE, no body

Client Error Codes:

  • 400 Bad Request: Invalid input, validation error
  • 401 Unauthorized: Missing or invalid authentication
  • 403 Forbidden: Authenticated but insufficient permissions
  • 404 Not Found: Resource doesn't exist
  • 409 Conflict: State conflict (duplicate, version mismatch)
  • 422 Unprocessable Entity: Semantic validation error
  • 429 Too Many Requests: Rate limit exceeded

Server Error Codes:

  • 500 Internal Server Error: Unexpected error
  • 502 Bad Gateway: Upstream service error
  • 503 Service Unavailable: Temporary outage
  • 504 Gateway Timeout: Upstream timeout

Error Response Format

Consistent error structure

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format",
        "code": "INVALID_FORMAT"
      }
    ],
    "request_id": "req_abc123",
    "documentation_url": "https://api.example.com/docs/errors/validation"
  }
}

Pagination Patterns

Offset Pagination (simple, familiar):

GET /users?limit=20&offset=40

✅ Use for: Small datasets, admin interfaces ❌ Avoid for: Large datasets (skips become expensive), real-time data

Cursor Pagination (stable, efficient):

GET /users?limit=20&cursor=eyJpZCI6MTIzfQ
Response: { "data": [...], "next_cursor": "eyJpZCI6MTQzfQ" }

✅ Use for: Infinite scroll, real-time feeds, large datasets ❌ Avoid for: Random access, page numbers

Keyset Pagination (performant):

GET /users?limit=20&after_id=123

✅ Use for: Ordered data, database index friendly ❌ Avoid for: Complex sorting, multiple sort keys

See references/rest-patterns.md for filtering, sorting, field selection, HATEOAS

GraphQL Patterns

Schema Design

Good: Clear types, nullable by default

type User {
  id: ID!                    # Non-null ID
  email: String!             # Required field
  name: String               # Optional (nullable by default)
  createdAt: DateTime!
  orders: [Order!]!          # Non-null array of non-null orders
}

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

type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
}

input CreateUserInput {
  email: String!
  name: String
}

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

Resolver Patterns

Avoid N+1 Queries with DataLoader:

import DataLoader from 'dataloader';

const userLoader = new DataLoader(async (userIds: string[]) => {
  const users = await db.users.findMany({ where: { id: { in: userIds } } });
  return userIds.map(id => users.find(u => u.id === id));
});

// Resolver batches queries automatically
const resolvers = {
  Order: {
    user: (order) => userLoader.load(order.userId)
  }
};

Query Complexity Analysis

Prevent expensive queries:

import { createComplexityLimitRule } from 'graphql-validation-complexity';

const server = new ApolloServer({
  schema,
  validationRules: [
    createComplexityLimitRule(1000, {
      onCost: (cost) => console.log('Query cost:', cost),
    }),
  ],
});

See references/graphql-patterns.md for subscriptions, relay cursor connections, error handling

gRPC Patterns

Service Definition

syntax = "proto3";

package users.v1;

service UserService {
  rpc GetUser (GetUserRequest) returns (User) {}
  rpc ListUsers (ListUsersRequest) returns (ListUsersResponse) {}
  rpc CreateUser (Cr
how to use api-design-patterns

How to use api-design-patterns on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add api-design-patterns
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill api-design-patterns

The skills CLI fetches api-design-patterns from GitHub repository bobmatnyc/claude-mpm-skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/api-design-patterns

Reload or restart Cursor to activate api-design-patterns. Access the skill through slash commands (e.g., /api-design-patterns) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.446 reviews
  • Chaitanya Patil· Dec 16, 2024

    I recommend api-design-patterns for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Amelia Khan· Dec 16, 2024

    We added api-design-patterns from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Charlotte Thompson· Dec 12, 2024

    api-design-patterns reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Charlotte Martinez· Dec 8, 2024

    Solid pick for teams standardizing on skills: api-design-patterns is focused, and the summary matches what you get after install.

  • Amelia Yang· Dec 4, 2024

    Registry listing for api-design-patterns matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Charlotte Harris· Nov 27, 2024

    api-design-patterns has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Piyush G· Nov 7, 2024

    api-design-patterns fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Chen Srinivasan· Nov 7, 2024

    api-design-patterns reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Neel Menon· Nov 3, 2024

    We added api-design-patterns from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Shikha Mishra· Oct 26, 2024

    api-design-patterns has been reliable in day-to-day use. Documentation quality is above average for community skills.

showing 1-10 of 46

1 / 5