Learn FastAPI best practices for architecture, auth, service layers, and testing.
Copy the install command and let the AI configure it · recommended for beginners
Please install the "fastapi-patterns" skill from askskill: 1. Download https://raw.githubusercontent.com/affaan-m/ECC/main/skills/fastapi-patterns/SKILL.md 2. Save it as ~/.claude/skills/fastapi-patterns/SKILL.md 3. Reload skills and tell me it's ready
Design a recommended project directory structure for a mid-sized FastAPI backend. Include API routes, Pydantic v2 schemas, service layer, repository layer, dependency injection, configuration management, and test folders, and explain each module's responsibility.
A clear directory tree, layer-by-layer explanation, and recommendations for maintainable scaling.
Give me a FastAPI authentication and authorization setup using dependency injection for JWT login, current user resolution, and role-based access control, with Pydantic v2 request and response models.
A reference API design, dependency functions, authorization patterns, and example code structure.
Create a test plan for a FastAPI async endpoint using pytest and httpx.AsyncClient. Cover successful responses, validation failures, authentication failures, and database transaction rollback scenarios.
A test case checklist, example test code, and common ways to organize tests.
Modern, production-grade FastAPI development: project layout, Pydantic v2 schemas, dependency injection, async patterns, auth, transactional service methods, and testing.
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/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()
# 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()
# 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):
total: int
items: list[UserResponse]
# app/dependencies.py
from typing import Annotated, AsyncGenerator
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
…
Compare prediction-market baskets with research notes to find gaps and alignment.
Coordinate behavior-preserving code refactors with tests, review, and gated commits.
Accelerate large-scale data pipelines, backfills, and syncs without sacrificing correctness.
Use Exa neural search for web, code, company, and people research.
Coordinate GitHub and Linear workflows for triage, tracking, and execution alignment.
Design security and risk controls for autonomous trading agents with transaction authority
Build HTTP service patterns with lifecycle hooks, WebSockets, SSE, and proxying.
Learn Django architecture, DRF API design, and production-ready development practices.
Apply NestJS architecture patterns to build maintainable production-ready TypeScript backends.
Get idiomatic C# and .NET guidance for architecture, async, and dependency injection.
Learn practical Kotlin Ktor server patterns for building and testing backend apps.
Learn frontend patterns for React, Next.js, state, performance, and UI best practices.