Generated banner for API Design Principles
Generated logo for API Design Principles

API Design Principles

Seth HobsonCommunityCreated by Seth Hobson

  • Skill
  • Guidelines
  • Software development
  • MIT
  • Low risk
  • Has scripts

From the author

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.
— the description by Seth Hobson

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to API design, covering core principles for both REST and GraphQL paradigms. It offers best practices for resource modeling, HTTP semantics, schema-first development, versioning, and error handling. Designed for developers and architects, it helps ensure APIs are consistent, developer-friendly, and built to evolve over time.

What it does

  • Defines RESTful resource-oriented architecture and HTTP method semantics.
  • Outlines GraphQL schema-first development and type design patterns.
  • Provides strategies for API versioning and evolution.
  • Details patterns for pagination, filtering, and sorting.
  • Establishes standards for consistent error handling and status codes.
  • Offers guidance on modular schema organization and polymorphism.

When to use it

  • When designing the architecture for a new API service.
  • When refactoring existing endpoints to improve usability and consistency.
  • When establishing organizational standards for API development.
  • During the review phase of an API specification before implementation.
  • When migrating or evaluating between REST and GraphQL paradigms.

Advantages

  • Promotes consistency across API surfaces, reducing developer friction.
  • Encourages scalable design patterns that handle growth and complexity.
  • Provides clear, actionable patterns for common API challenges like pagination.
  • Supports better maintainability through structured versioning and deprecation strategies.

Usage examples

“How should I structure my REST endpoints for a user management system?”
The agent will recommend a resource-oriented approach using plural nouns (e.g., /users) and standard HTTP methods (GET, POST, PUT, PATCH, DELETE) for operations.
“What is the best way to handle pagination in a GraphQL API?”
The agent will explain the Relay Cursor Pagination pattern, providing the necessary schema structure for edges, nodes, and pageInfo.
“How can I ensure consistent error responses across my API?”
The agent will suggest a standardized error payload structure including error codes, messages, and optional details, along with appropriate HTTP status codes.
“Should I use URL or header versioning for my API?”
The agent will compare the two approaches, explaining the trade-offs of each to help you decide based on your team's specific requirements.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/wshobson/api-design-principles/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip api-design-principles.zip -d .agents/skills

Documentation by Seth Hobson

API Design Principles

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers and stand the test of time.

When to Use This Skill

  • Designing new REST or GraphQL APIs

  • Refactoring existing APIs for better usability

  • Establishing API design standards for your team

  • Reviewing API specifications before implementation

  • Migrating between API paradigms (REST to GraphQL, etc.)

  • Creating developer-friendly API documentation

  • Optimizing APIs for specific use cases (mobile, third-party integrations)

Core Concepts

1. RESTful Design Principles

Resource-Oriented Architecture

  • Resources are nouns (users, orders, products), not verbs

  • Use HTTP methods for actions (GET, POST, PUT, PATCH, DELETE)

  • URLs represent resource hierarchies

  • Consistent naming conventions

HTTP Methods Semantics:

  • GET: Retrieve resources (idempotent, safe)

  • POST: Create new resources

  • PUT: Replace entire resource (idempotent)

  • PATCH: Partial resource updates

  • DELETE: Remove resources (idempotent)

2. GraphQL Design Principles

Schema-First Development

  • Types define your domain model

  • Queries for reading data

  • Mutations for modifying data

  • Subscriptions for real-time updates

Query Structure:

  • Clients request exactly what they need

  • Single endpoint, multiple operations

  • Strongly typed schema

  • Introspection built-in

3. API Versioning Strategies

URL Versioning:

/api/v1/users
/api/v2/users

Header Versioning:

Accept: application/vnd.api+json; version=1

Query Parameter Versioning:

/api/users?version=1

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Best Practices

REST APIs
  1. Consistent Naming: Use plural nouns for collections (/users, not /user)

  2. Stateless: Each request contains all necessary information

  3. Use HTTP Status Codes Correctly: 2xx success, 4xx client errors, 5xx server errors

  4. Version Your API: Plan for breaking changes from day one

  5. Pagination: Always paginate large collections

  6. Rate Limiting: Protect your API with rate limits

  7. Documentation: Use OpenAPI/Swagger for interactive docs

GraphQL APIs
  1. Schema First: Design schema before writing resolvers

  2. Avoid N+1: Use DataLoaders for efficient data fetching

  3. Input Validation: Validate at schema and resolver levels

  4. Error Handling: Return structured errors in mutation payloads

  5. Pagination: Use cursor-based pagination (Relay spec)

  6. Deprecation: Use @deprecated directive for gradual migration

  7. Monitoring: Track query complexity and execution time

Common Pitfalls

  • Over-fetching/Under-fetching (REST): Fixed in GraphQL but requires DataLoaders

  • Breaking Changes: Version APIs or use deprecation strategies

  • Inconsistent Error Formats: Standardize error responses

  • Missing Rate Limits: APIs without limits are vulnerable to abuse

  • Poor Documentation: Undocumented APIs frustrate developers

  • Ignoring HTTP Semantics: POST for idempotent operations breaks expectations

  • Tight Coupling: API structure shouldn't mirror database schema

Files

references/rest-best-practices.md

REST API Best Practices

URL Structure

Resource Naming
# Good - Plural nouns
GET /api/users
GET /api/orders
GET /api/products

# Bad - Verbs or mixed conventions
GET /api/getUser
GET /api/user  (inconsistent singular)
POST /api/createOrder
Nested Resources
# Shallow nesting (preferred)
GET /api/users/{id}/orders
GET /api/orders/{id}

# Deep nesting (avoid)
GET /api/users/{id}/orders/{orderId}/items/{itemId}/reviews
# Better:
GET /api/order-items/{id}/reviews

HTTP Methods and Status Codes

GET - Retrieve Resources
GET /api/users              → 200 OK (with list)
GET /api/users/{id}         → 200 OK or 404 Not Found
GET /api/users?page=2       → 200 OK (paginated)
POST - Create Resources
POST /api/users
  Body: {"name": "John", "email": "[email protected]"}
  → 201 Created
  Location: /api/users/123
  Body: {"id": "123", "name": "John", ...}

POST /api/users (validation error)
  → 422 Unprocessable Entity
  Body: {"errors": [...]}
PUT - Replace Resources
PUT /api/users/{id}
  Body: {complete user object}
  → 200 OK (updated)
  → 404 Not Found (doesn't exist)

# Must include ALL fields
PATCH - Partial Update
PATCH /api/users/{id}
  Body: {"name": "Jane"}  (only changed fields)
  → 200 OK
  → 404 Not Found
DELETE - Remove Resources
DELETE /api/users/{id}
  → 204 No Content (deleted)
  → 404 Not Found
  → 409 Conflict (can't delete due to references)

Filtering, Sorting, and Searching

Query Parameters
# Filtering
GET /api/users?status=active
GET /api/users?role=admin&status=active

# Sorting
GET /api/users?sort=created_at
GET /api/users?sort=-created_at  (descending)
GET /api/users?sort=name,created_at

# Searching
GET /api/users?search=john
GET /api/users?q=john

# Field selection (sparse fieldsets)
GET /api/users?fields=id,name,email

Pagination Patterns

Offset-Based Pagination
GET /api/users?page=2&page_size=20

Response:
{
  "items": [...],
  "page": 2,
  "page_size": 20,
  "total": 150,
  "pages": 8
}
Cursor-Based Pagination (for large datasets)
GET /api/users?limit=20&cursor=eyJpZCI6MTIzfQ

Response:
{
  "items": [...],
  "next_cursor": "eyJpZCI6MTQzfQ",
  "has_more": true
}
GET /api/users?page=2

Response Headers:
Link: <https://api.example.com/users?page=3>; rel="next",
      <https://api.example.com/users?page=1>; rel="prev",
      <https://api.example.com/users?page=1>; rel="first",
      <https://api.example.com/users?page=8>; rel="last"

Versioning Strategies

/api/v1/users
/api/v2/users

Pros: Clear, easy to route
Cons: Multiple URLs for same resource
Header Versioning
GET /api/users
Accept: application/vnd.api+json; version=2

Pros: Clean URLs
Cons: Less visible, harder to test
Query Parameter
GET /api/users?version=2

Pros: Easy to test
Cons: Optional parameter can be forgotten

Rate Limiting

Headers
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 742
X-RateLimit-Reset: 1640000000

Response when limited:
429 Too Many Requests
Retry-After: 3600
Implementation Pattern
from fastapi import HTTPException, Request
from datetime import datetime, timedelta

class RateLimiter:
    def __init__(self, calls: int, period: int):
        self.calls = calls
        self.period = period
        self.cache = {}

    def check(self, key: str) -> bool:
        now = datetime.now()
        if key not in self.cache:
            self.cache[key] = []

        # Remove old requests
        self.cache[key] = [
            ts for ts in self.cache[key]
            if now - ts < timedelta(seconds=self.period)
        ]

        if len(self.cache[key]) >= self.calls:
            return False

        self.cache[key].append(now)
        return True

limiter = RateLimiter(calls=100, period=60)

@app.get("/api/users")
async def get_users(request: Request):
    if not limiter.check(request.client.host):
        raise HTTPException(
            status_code=429,
            headers={"Retry-After": "60"}
        )
    return {"users": [...]}

Authentication and Authorization

Bearer Token
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

401 Unauthorized - Missing/invalid token
403 Forbidden - Valid token, insufficient permissions
API Keys
X-API-Key: your-api-key-here

Error Response Format

Consistent Structure
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format",
        "value": "not-an-email"
      }
    ],
    "timestamp": "2025-10-16T12:00:00Z",
    "path": "/api/users"
  }
}
Status Code Guidelines
  • 200 OK: Successful GET, PATCH, PUT

  • 201 Created: Successful POST

  • 204 No Content: Successful DELETE

  • 400 Bad Request: Malformed request

  • 401 Unauthorized: Authentication required

  • 403 Forbidden: Authenticated but not authorized

  • 404 Not Found: Resource doesn't exist

  • 409 Conflict: State conflict (duplicate email, etc.)

  • 422 Unprocessable Entity: Validation errors

  • 429 Too Many Requests: Rate limited

  • 500 Internal Server Error: Server error

  • 503 Service Unavailable: Temporary downtime

Caching

Cache Headers
# Client caching
Cache-Control: public, max-age=3600

# No caching
Cache-Control: no-cache, no-store, must-revalidate

# Conditional requests
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"
→ 304 Not Modified

Bulk Operations

Batch Endpoints
POST /api/users/batch
{
  "items": [
    {"name": "User1", "email": "[email protected]"},
    {"name": "User2", "email": "[email protected]"}
  ]
}

Response:
{
  "results": [
    {"id": "1", "status": "created"},
    {"id": null, "status": "failed", "error": "Email already exists"}
  ]
}

Idempotency

Idempotency Keys
POST /api/orders
Idempotency-Key: unique-key-123

If duplicate request:
→ 200 OK (return cached response)

CORS Configuration

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://example.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Documentation with OpenAPI

from fastapi import FastAPI

app = FastAPI(
    title="My API",
    description="API for managing users",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

@app.get(
    "/api/users/{user_id}",
    summary="Get user by ID",
    response_description="User details",
    tags=["Users"]
)
async def get_user(
    user_id: str = Path(..., description="The user ID")
):
    """
    Retrieve user by ID.

    Returns full user profile including:
    - Basic information
    - Contact details
    - Account status
    """
    pass

Health and Monitoring Endpoints

@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "version": "1.0.0",
        "timestamp": datetime.now().isoformat()
    }

@app.get("/health/detailed")
async def detailed_health():
    return {
        "status": "healthy",
        "checks": {
            "database": await check_database(),
            "redis": await check_redis(),
            "external_api": await check_external_api()
        }
    }

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Seth Hobson
Publisher
Seth Hobson (Community)
Source
wshobson/agents · plugins/backend-development/skills/api-design-principles · commit 4bde316
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Seth Hobson.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download api-design-principles.zip