Skip to main content
< All Topics
Print

FastAPI Development

name: fastapi-development

description: Build FastAPI applications with async endpoints, Pydantic validation, dependency injection, and containerized deployment. Use when developing Python APIs with FastAPI, designing async database access, structuring middleware, or deploying with Docker and Uvicorn.

FastAPI Development

Instructions

Build production-grade FastAPI applications following these patterns.

Async endpoint design:

  • Use async def for endpoints performing I/O (database queries, HTTP calls, file operations)
  • Use plain def for CPU-bound endpoints — FastAPI runs them in a thread pool automatically
  • Await all async calls; never mix sync blocking calls inside async def endpoints

Pydantic models for request/response:

  • Define request bodies as Pydantic BaseModel subclasses with type annotations and validators
  • Define response models with response_model parameter on route decorators to control serialization
  • Use Field(...) for validation constraints (min_length, ge, le, regex)
  • Separate create, update, and response schemas (e.g., UserCreate, UserUpdate, UserResponse)

Dependency injection:

  • Use Depends() for database sessions, authenticated users, configuration, and shared services
  • Create generator dependencies with yield for resource lifecycle management (open/close DB sessions)
  • Layer dependencies: auth depends on DB session, endpoint depends on auth
  • Define reusable dependencies in a dedicated deps.py module

SQLAlchemy async with asyncpg:

  • Use create_async_engine with asyncpg driver for PostgreSQL (postgresql+asyncpg://)
  • Create sessions with async_sessionmaker and AsyncSession
  • Use select() statements with await session.execute() — avoid legacy Query API
  • Run migrations with Alembic configured for async (run_async)

Middleware:

  • Add CORSMiddleware with explicit allow_origins, allow_methods, allow_headers
  • Implement custom middleware for request logging, timing, and authentication token validation
  • Order matters: middleware executes in reverse declaration order

Docker deployment:

  • Use multi-stage builds: builder stage installs dependencies, runtime stage copies only what’s needed
  • Run with Uvicorn: uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4
  • Set --workers based on CPU cores (2 × cores + 1 as starting point)
  • Use health check endpoint (/health) in Docker Compose and orchestrators

Patriot University reference architecture:

  • FastAPI application server with PostgreSQL 16 for relational data
  • Redis 7 for caching, session storage, and rate limiting
  • MinIO for S3-compatible object storage (documents, media)
  • Docker Compose orchestration with service health checks and restart policies
Table of Contents