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://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

assets/rest-api-template.py

"""
Production-ready REST API template using FastAPI.
Includes pagination, filtering, error handling, and best practices.
"""

from fastapi import FastAPI, HTTPException, Query, Path, Depends, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, EmailStr, ConfigDict
from typing import Optional, List, Any
from datetime import datetime
from enum import Enum

app = FastAPI(
    title="API Template",
    version="1.0.0",
    docs_url="/api/docs"
)

# Security Middleware
# Trusted Host: Prevents HTTP Host Header attacks
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["*"] # TODO: Configure this in production, e.g. ["api.example.com"]
)

# CORS: Configures Cross-Origin Resource Sharing
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"], # TODO: Update this with specific origins in production
    allow_credentials=False, # TODO: Set to True if you need cookies/auth headers, but restrict origins
    allow_methods=["*"],
    allow_headers=["*"],
)

# Models
class UserStatus(str, Enum):
    ACTIVE = "active"
    INACTIVE = "inactive"
    SUSPENDED = "suspended"

class UserBase(BaseModel):
    email: EmailStr
    name: str = Field(..., min_length=1, max_length=100)
    status: UserStatus = UserStatus.ACTIVE

class UserCreate(UserBase):
    password: str = Field(..., min_length=8)

class UserUpdate(BaseModel):
    email: Optional[EmailStr] = None
    name: Optional[str] = Field(None, min_length=1, max_length=100)
    status: Optional[UserStatus] = None

class User(UserBase):
    id: str
    created_at: datetime
    updated_at: datetime

    model_config = ConfigDict(from_attributes=True)

# Pagination
class PaginationParams(BaseModel):
    page: int = Field(1, ge=1)
    page_size: int = Field(20, ge=1, le=100)

class PaginatedResponse(BaseModel):
    items: List[Any]
    total: int
    page: int
    page_size: int
    pages: int

# Error handling
class ErrorDetail(BaseModel):
    field: Optional[str] = None
    message: str
    code: str

class ErrorResponse(BaseModel):
    error: str
    message: str
    details: Optional[List[ErrorDetail]] = None

@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return JSONResponse(
        status_code=exc.status_code,
        content=ErrorResponse(
            error=exc.__class__.__name__,
            message=exc.detail if isinstance(exc.detail, str) else exc.detail.get("message", "Error"),
            details=exc.detail.get("details") if isinstance(exc.detail, dict) else None
        ).model_dump()
    )

# Endpoints
@app.get("/api/users", response_model=PaginatedResponse, tags=["Users"])
async def list_users(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    status: Optional[UserStatus] = Query(None),
    search: Optional[str] = Query(None)
):
    """List users with pagination and filtering."""
    # Mock implementation
    total = 100
    items = [
        User(
            id=str(i),
            email=f"user{i}@example.com",
            name=f"User {i}",
            status=UserStatus.ACTIVE,
            created_at=datetime.now(),
            updated_at=datetime.now()
        ).model_dump()
        for i in range((page-1)*page_size, min(page*page_size, total))
    ]

    return PaginatedResponse(
        items=items,
        total=total,
        page=page,
        page_size=page_size,
        pages=(total + page_size - 1) // page_size
    )

@app.post("/api/users", response_model=User, status_code=status.HTTP_201_CREATED, tags=["Users"])
async def create_user(user: UserCreate):
    """Create a new user."""
    # Mock implementation
    return User(
        id="123",
        email=user.email,
        name=user.name,
        status=user.status,
        created_at=datetime.now(),
        updated_at=datetime.now()
    )

@app.get("/api/users/{user_id}", response_model=User, tags=["Users"])
async def get_user(user_id: str = Path(..., description="User ID")):
    """Get user by ID."""
    # Mock: Check if exists
    if user_id == "999":
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail={
                "message": "User not found",
                "details": [{"field": "user_id", "message": f"No user with ID {user_id}", "code": "not_found"}],
            }
        )

    return User(
        id=user_id,
        email="[email protected]",
        name="User Name",
        status=UserStatus.ACTIVE,
        created_at=datetime.now(),
        updated_at=datetime.now()
    )

@app.patch("/api/users/{user_id}", response_model=User, tags=["Users"])
async def update_user(user_id: str, update: UserUpdate):
    """Partially update user."""
    # Validate user exists
    existing = await get_user(user_id)

    # Apply updates
    update_data = update.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(existing, field, value)

    existing.updated_at = datetime.now()
    return existing

@app.delete("/api/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT, tags=["Users"])
async def delete_user(user_id: str):
    """Delete user."""
    await get_user(user_id)  # Verify exists
    return None

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

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 or Seth Hobson.

Download ZIP

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