skills/python-fastapi/SKILL.md
Building REST APIs with FastAPI, Pydantic validation, and OpenAPI. Use when creating routes, handling requests, designing endpoints, implementing validation, error responses, pagination, or generating API documentation.
npx skillsauth add martinffx/claude-code-atelier python-fastapiInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
FastAPI is a modern, fast web framework for building APIs with Python, using standard Python type hints. FastAPI automatically validates requests, generates OpenAPI documentation, and provides excellent developer experience.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(
title="My API",
description="API for my application",
version="1.0.0",
)
class Item(BaseModel):
name: str
price: float
@app.get("/")
def read_root():
return {"message": "Hello World"}
@app.post("/items", response_model=Item)
def create_item(item: Item):
return item
Run with:
uvicorn main:app --reload
Use Pydantic models for automatic validation and serialization:
from pydantic import BaseModel, EmailStr, Field
class CreateUserRequest(BaseModel):
email: EmailStr
name: str = Field(min_length=1, max_length=100)
age: int = Field(ge=18, le=120)
class UserResponse(BaseModel):
id: int
email: str
name: str
model_config = {"from_attributes": True} # Enable ORM mode
@app.post("/users", response_model=UserResponse)
def create_user(user: CreateUserRequest):
"""Request validated, response serialized automatically"""
return user
See references/validation.md for detailed validation patterns including custom validators and field constraints.
Split routes across routers for clean organization:
# routers/users.py
from fastapi import APIRouter
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/")
def list_users():
...
@router.post("/")
def create_user(user: CreateUserRequest):
...
# main.py
app.include_router(users.router)
FastAPI's core feature for managing dependencies like database sessions and authentication:
from fastapi import Depends
from sqlalchemy.orm import Session
def get_db() -> Session:
"""Database session dependency"""
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users")
def list_users(db: Session = Depends(get_db)):
"""db automatically injected"""
return db.query(User).all()
See references/dependencies.md for advanced patterns including auth services, scoped dependencies, and dependency classes.
from fastapi import HTTPException
@app.get("/users/{user_id}")
def get_user(user_id: int):
user = db.get(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
from fastapi import Request
from fastapi.responses import JSONResponse
class BusinessError(Exception):
def __init__(self, message: str):
self.message = message
@app.exception_handler(BusinessError)
async def business_error_handler(request: Request, exc: BusinessError):
return JSONResponse(
status_code=400,
content={"error": exc.message},
)
my-api/
├── main.py # FastAPI app
├── routers/ # Route handlers
│ ├── users.py
│ └── products.py
├── schemas/ # Pydantic models
│ ├── users.py
│ └── products.py
├── services/ # Business logic
│ └── users.py
├── repositories/ # Data access
│ └── users.py
└── dependencies.py # Dependency injection
Detailed patterns for common scenarios:
references/validation.md - Field constraints, custom validators, model validationreferences/dependencies.md - Auth services, scoped dependencies, advanced injection patternsreferences/middleware.md - CORS, custom middleware, request/response processingreferences/api-design.md - REST naming, pagination, OpenAPI customization, status codesdevelopment
Security architecture and threat modeling knowledge. Auto-invokes when designing features that handle untrusted data, authentication, authorization, external integrations, file uploads, or sensitive data. Provides risk assessment frameworks, trust boundary analysis, and security design principles — not implementation code.
testing
Adversarial review of non-trivial decisions using fresh-context scrutiny. Use when correctness matters more than speed, when stakes are high (production, security-sensitive logic, irreversible operations), or before committing significant architectural or implementation choices.
development
Compact the current conversation into a handoff document for another agent to pick up.
testing
Socratic interrogation of plans against the project's domain model and documented decisions. Use when the user wants to stress-test a plan, clarify terminology, or validate assumptions against existing domain language. Updates CONTEXT.md and ADRs inline as decisions crystallise.