@tank/fastapi-mastery
1.0.0Description
Production FastAPI patterns covering project structure, Depends-based DI, Pydantic v2, async SQLAlchemy, auth, middleware, testing, deployment, and performance.
Triggered by
fastapidependency injectionpydanticsqlalchemyjwttesting
Download
Verified
tank install @tank/fastapi-masteryFastAPI Mastery
Core Philosophy
- Type hints are the contract -- FastAPI derives validation, serialization, and OpenAPI docs from type annotations. Invest in precise types and Pydantic models; everything downstream improves.
- Dependencies replace globals -- Use
Depends()for database sessions, settings, auth, and shared logic. Dependencies are composable, testable, and self-documenting. - Async by default, sync when blocking -- Use
async deffor I/O-bound routes (database, HTTP calls). Usedeffor CPU-bound work so FastAPI runs it in a thread pool automatically. - Thin routes, fat services -- Route functions validate input and return output. Business logic belongs in service classes injected via dependencies.
- Test through the API -- Use
TestClientwith dependency overrides. Test behavior, not implementation. Override only what varies between environments.
Quick-Start: Common Problems
"How should I structure my FastAPI project?"
| Project Size | Structure |
|---|---|
| Small (< 10 routes) | Single main.py with inline routes |
| Medium (10-50 routes) | Feature-based: app/{feature}/router.py, service.py, models.py |
| Large (50+ routes) | Layered: routers -> services -> repositories + shared core/ |
- Group by feature, not by file type (no
routers/,models/,services/top-level dirs) - Each feature module gets its own router, schemas, and service
- Wire routers in
main.pywithapp.include_router()-> Seereferences/project-structure.md
"My dependency injection is getting complicated"
- Use
Annotatedtype aliases to avoid repeatingDepends()signatures - Use
yielddependencies for setup/teardown (database sessions, file handles) - Chain sub-dependencies -- FastAPI resolves the full dependency tree automatically
- Override dependencies in tests with
app.dependency_overrides[original] = mock-> Seereferences/dependency-injection.md
"How do I set up the database properly?"
- Use SQLAlchemy 2.0 async with
create_async_engineandasync_sessionmaker - Inject sessions via a
yielddependency -- session per request, auto-cleanup - Set
expire_on_commit=Falsefor async sessions to avoid lazy-load errors - Use Alembic with async driver for migrations
-> See
references/database-integration.md
"What auth pattern should I use?"
| Scenario | Pattern |
|---|---|
| SPA / mobile calling your API | OAuth2 + JWT (access + refresh tokens) |
| Server-to-server | API key or Client Credentials |
| Simple internal tool | API key in header |
| Third-party integration | OAuth2 scopes |
-> See references/authentication.md
"My tests are slow or flaky"
- Use
TestClientfor sync tests -- noasyncoverhead - Override database dependency to use a test database
- Use
httpx.AsyncClientonly when testing async-specific behavior - Create fixtures for authenticated clients and test data
-> See
references/testing.md
Decision Trees
Async vs Sync Route
| Operation | Use |
|---|---|
| Database queries (SQLAlchemy async) | async def |
| HTTP calls (httpx, aiohttp) | async def |
| File I/O (large files) | async def with aiofiles |
| CPU-bound (image processing, ML) | def (runs in thread pool) |
| Blocking library (no async support) | def |
Background Processing
| Task Duration | Tool |
|---|---|
| < 5 seconds, fire-and-forget | BackgroundTasks |
| 5-30 seconds, needs monitoring | BackgroundTasks with status tracking |
| > 30 seconds, retry logic, scheduling | Celery + Redis/RabbitMQ |
| Real-time progress updates | WebSocket + task queue |
Database Library
| Need | Choice |
|---|---|
| Full ORM control, complex queries | SQLAlchemy 2.0 async |
| Rapid prototyping, simpler models | SQLModel (SQLAlchemy + Pydantic) |
| Raw SQL, maximum performance | encode/databases or asyncpg directly |
Reference Index
| File | Contents |
|---|---|
references/project-structure.md | Directory layouts, feature-based modules, router wiring, configuration management with Pydantic Settings, application factory pattern |
references/dependency-injection.md | Depends patterns, yield dependencies, sub-dependencies, class-based deps, Annotated aliases, global dependencies, dependency overrides |
references/pydantic-models.md | Pydantic v2 models, field validation, custom validators, serialization, discriminated unions, model_config, request/response schema design |
references/database-integration.md | SQLAlchemy 2.0 async setup, session management, repository pattern, Alembic migrations, connection pooling, transaction handling |
references/authentication.md | OAuth2PasswordBearer, JWT access/refresh tokens, API key auth, scopes, role-based access, security dependencies |
references/middleware-errors.md | CORS, custom middleware, exception handlers, request validation errors, logging middleware, request ID tracking |
references/testing.md | TestClient, async tests, dependency overrides, database test fixtures, authentication testing, factory patterns |
references/deployment.md | Uvicorn workers, Docker multi-stage builds, Kubernetes probes, gunicorn, serverless (Mangum), environment configuration |
references/async-performance.md | Async patterns, BackgroundTasks, Celery integration, WebSockets, streaming responses, caching, connection pooling, profiling |