Skip to content

@tank/fastapi-mastery

1.0.0

Description

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-mastery

FastAPI Mastery

Core Philosophy

  1. 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.
  2. Dependencies replace globals -- Use Depends() for database sessions, settings, auth, and shared logic. Dependencies are composable, testable, and self-documenting.
  3. Async by default, sync when blocking -- Use async def for I/O-bound routes (database, HTTP calls). Use def for CPU-bound work so FastAPI runs it in a thread pool automatically.
  4. Thin routes, fat services -- Route functions validate input and return output. Business logic belongs in service classes injected via dependencies.
  5. Test through the API -- Use TestClient with dependency overrides. Test behavior, not implementation. Override only what varies between environments.

Quick-Start: Common Problems

"How should I structure my FastAPI project?"

Project SizeStructure
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/
  1. Group by feature, not by file type (no routers/, models/, services/ top-level dirs)
  2. Each feature module gets its own router, schemas, and service
  3. Wire routers in main.py with app.include_router() -> See references/project-structure.md

"My dependency injection is getting complicated"

  1. Use Annotated type aliases to avoid repeating Depends() signatures
  2. Use yield dependencies for setup/teardown (database sessions, file handles)
  3. Chain sub-dependencies -- FastAPI resolves the full dependency tree automatically
  4. Override dependencies in tests with app.dependency_overrides[original] = mock -> See references/dependency-injection.md

"How do I set up the database properly?"

  1. Use SQLAlchemy 2.0 async with create_async_engine and async_sessionmaker
  2. Inject sessions via a yield dependency -- session per request, auto-cleanup
  3. Set expire_on_commit=False for async sessions to avoid lazy-load errors
  4. Use Alembic with async driver for migrations -> See references/database-integration.md

"What auth pattern should I use?"

ScenarioPattern
SPA / mobile calling your APIOAuth2 + JWT (access + refresh tokens)
Server-to-serverAPI key or Client Credentials
Simple internal toolAPI key in header
Third-party integrationOAuth2 scopes

-> See references/authentication.md

"My tests are slow or flaky"

  1. Use TestClient for sync tests -- no async overhead
  2. Override database dependency to use a test database
  3. Use httpx.AsyncClient only when testing async-specific behavior
  4. Create fixtures for authenticated clients and test data -> See references/testing.md

Decision Trees

Async vs Sync Route

OperationUse
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 DurationTool
< 5 seconds, fire-and-forgetBackgroundTasks
5-30 seconds, needs monitoringBackgroundTasks with status tracking
> 30 seconds, retry logic, schedulingCelery + Redis/RabbitMQ
Real-time progress updatesWebSocket + task queue

Database Library

NeedChoice
Full ORM control, complex queriesSQLAlchemy 2.0 async
Rapid prototyping, simpler modelsSQLModel (SQLAlchemy + Pydantic)
Raw SQL, maximum performanceencode/databases or asyncpg directly

Reference Index

FileContents
references/project-structure.mdDirectory layouts, feature-based modules, router wiring, configuration management with Pydantic Settings, application factory pattern
references/dependency-injection.mdDepends patterns, yield dependencies, sub-dependencies, class-based deps, Annotated aliases, global dependencies, dependency overrides
references/pydantic-models.mdPydantic v2 models, field validation, custom validators, serialization, discriminated unions, model_config, request/response schema design
references/database-integration.mdSQLAlchemy 2.0 async setup, session management, repository pattern, Alembic migrations, connection pooling, transaction handling
references/authentication.mdOAuth2PasswordBearer, JWT access/refresh tokens, API key auth, scopes, role-based access, security dependencies
references/middleware-errors.mdCORS, custom middleware, exception handlers, request validation errors, logging middleware, request ID tracking
references/testing.mdTestClient, async tests, dependency overrides, database test fixtures, authentication testing, factory patterns
references/deployment.mdUvicorn workers, Docker multi-stage builds, Kubernetes probes, gunicorn, serverless (Mangum), environment configuration
references/async-performance.mdAsync patterns, BackgroundTasks, Celery integration, WebSockets, streaming responses, caching, connection pooling, profiling

Command Palette

Search skills, docs, and navigate Tank