fastapi-api-patterns
REST API design and implementation patterns for FastAPI endpoints including CRUD operations, pagination, filtering, error handling, and request/response models. Use when building FastAPI endpoints, creating REST APIs, implementing CRUD operations, adding pagination, designing API routes, handling API errors, or when user mentions FastAPI patterns, REST API design, endpoint structure, API best practices, or HTTP endpoints.
What this skill does
# fastapi-api-patterns
## Instructions
This skill provides comprehensive REST API design patterns and implementation templates for FastAPI applications. It covers CRUD operations, pagination, filtering, request/response models, error handling, and API organization following modern best practices.
### 1. CRUD Endpoint Patterns
Create, Read, Update, Delete endpoints using FastAPI routers:
```bash
# Use CRUD template to generate complete endpoint set
cp ./skills/fastapi-api-patterns/templates/crud_endpoint.py app/routers/items.py
# Customize for your model
# - Replace Item model with your Pydantic model
# - Update database operations
# - Add authentication dependencies
```
**What This Provides:**
- `POST /items/` - Create new item
- `GET /items/{item_id}` - Read single item by ID
- `GET /items/` - Read multiple items with pagination
- `PUT /items/{item_id}` - Update entire item
- `PATCH /items/{item_id}` - Partial update
- `DELETE /items/{item_id}` - Delete item
**Router Structure:**
```python
from fastapi import APIRouter, HTTPException, Depends, status
from typing import List
router = APIRouter(
prefix="/items",
tags=["items"],
responses={404: {"description": "Not found"}},
)
```
### 2. Pagination and Filtering
Implement pagination with query parameters:
```bash
# Use pagination template
cp ./skills/fastapi-api-patterns/templates/pagination.py app/utils/pagination.py
```
**Pagination Strategies:**
**1. Offset-Based Pagination (Simple):**
```python
@router.get("/items/")
async def list_items(skip: int = 0, limit: int = 10):
return items[skip : skip + limit]
```
**2. Cursor-Based Pagination (Performance):**
```python
@router.get("/items/")
async def list_items(cursor: str | None = None, limit: int = 10):
# Use last item ID as cursor for next page
# Better for large datasets
```
**3. Page-Based Pagination (User-Friendly):**
```python
@router.get("/items/")
async def list_items(page: int = 1, page_size: int = 10):
skip = (page - 1) * page_size
return items[skip : skip + page_size]
```
**Filtering Patterns:**
```python
@router.get("/items/")
async def list_items(
skip: int = 0,
limit: int = 10,
category: str | None = None,
min_price: float | None = None,
max_price: float | None = None,
search: str | None = None,
):
# Apply filters before pagination
filtered_items = apply_filters(items, category, min_price, max_price, search)
return filtered_items[skip : skip + limit]
```
**Sorting:**
```python
from enum import Enum
class SortBy(str, Enum):
name = "name"
price = "price"
created_at = "created_at"
@router.get("/items/")
async def list_items(
sort_by: SortBy = SortBy.created_at,
order: Literal["asc", "desc"] = "desc",
):
# Sort before returning
```
### 3. Request and Response Models
Define clear Pydantic models for type safety and validation:
**Base Models:**
```python
from pydantic import BaseModel, Field, validator
from datetime import datetime
class ItemBase(BaseModel):
"""Shared properties"""
name: str = Field(..., min_length=1, max_length=100)
description: str | None = Field(None, max_length=500)
price: float = Field(..., gt=0)
category: str
class ItemCreate(ItemBase):
"""Properties required for creation"""
pass
class ItemUpdate(BaseModel):
"""Properties that can be updated"""
name: str | None = None
description: str | None = None
price: float | None = Field(None, gt=0)
category: str | None = None
class ItemInDB(ItemBase):
"""Properties stored in database"""
id: int
created_at: datetime
updated_at: datetime
class Item(ItemInDB):
"""Properties returned to client"""
class Config:
from_attributes = True
```
**Response Models with Metadata:**
```python
from typing import Generic, TypeVar, List
from pydantic import BaseModel
T = TypeVar('T')
class PaginatedResponse(BaseModel, Generic[T]):
items: List[T]
total: int
page: int
page_size: int
pages: int
@router.get("/items/", response_model=PaginatedResponse[Item])
async def list_items(page: int = 1, page_size: int = 10):
total = len(items)
pages = (total + page_size - 1) // page_size
skip = (page - 1) * page_size
return PaginatedResponse(
items=items[skip : skip + page_size],
total=total,
page=page,
page_size=page_size,
pages=pages,
)
```
### 4. Error Handling Strategies
Implement consistent error handling:
```bash
# Use error handling template
cp ./skills/fastapi-api-patterns/templates/error_handling.py app/utils/errors.py
```
**HTTP Exception Patterns:**
```python
from fastapi import HTTPException, status
# 404 Not Found
if item is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Item with id {item_id} not found"
)
# 400 Bad Request
if price < 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Price must be positive"
)
# 409 Conflict
if item_exists:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Item with this name already exists"
)
# 403 Forbidden
if not is_owner:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to modify this item"
)
```
**Custom Exception Handlers:**
```python
from fastapi import Request
from fastapi.responses import JSONResponse
class ItemNotFoundError(Exception):
def __init__(self, item_id: int):
self.item_id = item_id
@app.exception_handler(ItemNotFoundError)
async def item_not_found_handler(request: Request, exc: ItemNotFoundError):
return JSONResponse(
status_code=404,
content={
"error": "not_found",
"message": f"Item {exc.item_id} not found",
"item_id": exc.item_id
}
)
```
**Validation Error Customization:**
```python
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={
"error": "validation_error",
"message": "Invalid request data",
"details": exc.errors()
}
)
```
### 5. Dependency Injection for Common Logic
Use dependencies for authentication, database sessions, and validation:
```python
from fastapi import Depends, Header, HTTPException
# Authentication dependency
async def verify_token(x_token: str = Header(...)):
if x_token != "secret-token":
raise HTTPException(status_code=401, detail="Invalid token")
return x_token
# Database session dependency
async def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# Pagination dependency
async def pagination_params(
skip: int = 0,
limit: int = 10,
max_limit: int = 100
):
if limit > max_limit:
limit = max_limit
return {"skip": skip, "limit": limit}
# Use in endpoints
@router.get("/items/")
async def list_items(
token: str = Depends(verify_token),
db: Session = Depends(get_db),
pagination: dict = Depends(pagination_params),
):
return db.query(Item).offset(pagination["skip"]).limit(pagination["limit"]).all()
```
### 6. API Router Organization
Structure APIs with APIRouter for modularity:
```python
# app/routers/items.py
from fastapi import APIRouter
router = APIRouter(
prefix="/items",
tags=["items"],
dependencies=[Depends(verify_token)],
responses={404: {"description": "Not found"}},
)
# app/main.py
from fastapi import FastAPI
from app.routers import items, users
app = FastAPI()
app.include_router(items.router)
app.include_router(users.router, prefix="/api/v1")
```
### 7. OpenAPI Documentation Enhancement
Generate better API documentation:
```bash
# GeneRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.