
Fastapi Patterns
Scaffold and extend a production FastAPI service with Pydantic v2, DI, async routes, auth, and httpx/pytest tests.
Overview
FastAPI Patterns is an agent skill for the Build phase that teaches production-grade FastAPI structure, Pydantic v2, dependency injection, async handlers, auth, transactional services, and httpx/pytest testing.
Install
npx skills add https://github.com/affaan-m/everything-claude-code --skill fastapi-patternsWhat is this skill?
- Layered layout: routers, schemas, services, SQLAlchemy models, and shared dependencies
- App factory with lifespan hooks, CORS middleware, and pydantic-settings config
- Pydantic v2 request/response models and dependency-injection patterns for handlers
- Async handlers plus auth, authorization, and transactional service-layer patterns
- Testing stack with httpx and pytest fixtures in conftest
Adoption & trust: 1.2k installs on skills.sh; 210k GitHub stars; 3/3 security scanners passed (skills.sh audits).
What problem does it solve?
You are building a FastAPI API but your agent keeps mixing routes, schemas, and DB logic without a repeatable production layout or test pattern.
Who is it for?
Indie builders creating or hardening a Python REST API with FastAPI, SQLAlchemy, and pytest who want agent output to match team-style structure.
Skip if: Teams that only need a single throwaway script, a non-Python stack, or a project where architecture is already frozen and documented elsewhere.
When should I use this skill?
When implementing or extending a FastAPI backend with production layout, Pydantic v2 schemas, DI, async handlers, auth, services, and httpx/pytest tests.
What do I get? / Deliverables
After the skill runs, you get a coherent FastAPI project pattern—factory app, layered modules, DI, auth hooks, and API tests—you can apply file-by-file in your repo.
- Layered FastAPI module layout
- Router and schema patterns
- pytest/httpx test scaffolding
Recommended Skills
Journey fit
How it compares
Use as procedural backend guidance in the agent, not as a hosted framework or MCP server that runs your API for you.
Common Questions / FAQ
Who is fastapi-patterns for?
Solo and indie developers using AI coding agents to implement or refactor FastAPI backends with SQLAlchemy, Pydantic v2, and standard pytest/httpx tests.
When should I use fastapi-patterns?
During Build when you are laying out routers and services, adding auth to routes, or writing API tests—especially at the start of a new FastAPI module or service layer.
Is fastapi-patterns safe to install?
It is documentation-style skill content without bundled scrapers; review the Security Audits panel on this Prism page and only grant your agent permissions your repo needs.
SKILL.md
READMESKILL.md - Fastapi Patterns
# FastAPI Patterns Modern, production-grade FastAPI development: project layout, Pydantic v2 schemas, dependency injection, async patterns, auth, transactional service methods, and testing. ## Project Structure ```text my_app/ |-- app/ | |-- main.py # App factory, lifespan, middleware | |-- config.py # Settings via pydantic-settings | |-- dependencies.py # Shared FastAPI dependencies | |-- database.py # SQLAlchemy engine + session | |-- routers/ | | `-- users.py | |-- models/ # SQLAlchemy ORM models | | `-- user.py | |-- schemas/ # Pydantic request/response schemas | | `-- user.py | `-- services/ # Business logic layer | `-- user_service.py |-- tests/ | |-- conftest.py | `-- test_users.py |-- pyproject.toml `-- .env ``` --- ## App Factory and Lifespan ```python # app/main.py from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.config import settings from app.database import engine, Base from app.routers import users @asynccontextmanager async def lifespan(app: FastAPI): # Automatically create tables on startup for ease of use in dev/demo environments. # For strict production applications, manage schemas via Alembic migrations instead. async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) yield # Shutdown: close pooled resources. await engine.dispose() def create_app() -> FastAPI: app = FastAPI( title=settings.app_name, version=settings.app_version, lifespan=lifespan, ) app.add_middleware( CORSMiddleware, allow_origins=settings.allowed_origins, allow_credentials=settings.allow_credentials, allow_methods=settings.allowed_methods, allow_headers=settings.allowed_headers, ) app.include_router(users.router, prefix="/users", tags=["users"]) return app app = create_app() ``` --- ## Configuration with pydantic-settings ```python # app/config.py from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8") app_name: str = "My App" app_version: str = "0.1.0" debug: bool = False database_url: str secret_key: str algorithm: str = "HS256" access_token_expire_minutes: int = 30 # Pydantic-settings v2 safely evaluates mutable list literals directly allowed_origins: list[str] = ["http://localhost:3000"] allowed_methods: list[str] = ["GET", "POST", "PATCH", "DELETE", "OPTIONS"] allowed_headers: list[str] = ["Authorization", "Content-Type"] allow_credentials: bool = True settings = Settings() ``` --- ## Pydantic Schemas (v2) ```python # app/schemas/user.py from datetime import datetime from pydantic import BaseModel, EmailStr, Field, model_validator class UserBase(BaseModel): email: EmailStr username: str = Field(min_length=3, max_length=50) class UserCreate(UserBase): password: str = Field(min_length=8) password_confirm: str @model_validator(mode="after") def passwords_match(self) -> "UserCreate": if self.password != self.password_confirm: raise ValueError("Passwords do not match") return self class UserUpdate(BaseModel): username: str | None = Field(default=None, min_length=3, max_length=50) email: EmailStr | None = None class UserResponse(UserBase): id: int is_active: bool created_at: datetime model_config = {"from_attributes": True} class UserListResponse(BaseModel): tot