Resources

100 FastAPI resources for developers

A guide to building and scaling FastAPI applications with a focus on production-ready architecture, high-performance database management, and modern AI/LLM integration patterns.

Production Architecture and Project Templates

  1. 1

    Full Stack FastAPI Template

    intermediatehigh

    The official Tiangolo production-ready template including PostgreSQL, Docker, Celery, and a Vue frontend. Use it to understand the recommended project layout with separate services and alembic migrations.

  2. 2

    FastAPI Best Practices Repository

    beginnerstandard

    A curated list of architectural patterns on GitHub (zhanymkanov/fastapi-best-practices) covering folder structure, dependency injection, and centralized exception handling.

  3. 3

    SQLModel Integration

    intermediatehigh

    Use SQLModel to eliminate code duplication between Pydantic models and SQLAlchemy entities. This reduces the surface area for bugs in larger applications.

  4. 4

    Modular APIRouter Implementation

    beginnerstandard

    Break down large APIs into domain-specific modules using fastapi.APIRouter. Mount them in a main.py file to maintain clean namespaces and manageable file sizes.

  5. 5

    FastAPI Versioning

    intermediatestandard

    Implement the fastapi-versioning library to manage API lifecycle. It allows you to route requests based on header or URL versioning without duplicating the entire codebase.

  6. 6

    Dependency Injection for Service Layers

    intermediatehigh

    Move business logic out of path operations and into service classes. Inject these services using FastAPI's Depends() to facilitate easier unit testing with mocks.

  7. 7

    Pydantic v2 Migration

    intermediatehigh

    Upgrade to Pydantic v2 for up to 20x performance improvement in data validation. Ensure all Field and Validator definitions are updated to the new syntax.

  8. 8

    FastAPI Pagination

    beginnerstandard

    Standardize list responses using the fastapi-pagination library. It supports multiple backends including SQLAlchemy, Tortoise, and Motor with minimal boilerplate.

  9. 9

    Custom Exception Handlers

    beginnerstandard

    Register global exception handlers using @app.exception_handler to return standardized JSON error schemas across the entire API.

  10. 10

    Cookiecutter FastAPI

    beginnerstandard

    A template for generating a FastAPI project with pre-configured Docker Compose, CI/CD pipelines, and environment variable management via Pydantic Settings.

Database Management and Async I/O

  1. 1

    SQLAlchemy 2.0 Async Session

    advancedhigh

    Implement the async version of SQLAlchemy's sessionmaker. Use the async_scoped_session for thread-safe operations in high-concurrency environments.

  2. 2

    Alembic Async Migrations

    intermediatestandard

    Configure Alembic to use the async driver (e.g., postgresql+asyncpg). Modify the env.py file to use run_async for database schema updates.

  3. 3

    Redis for Response Caching

    intermediatehigh

    Integrate redis-py (async) to cache expensive database queries. Use the fastapi-cache2 library to implement easy decorator-based caching on path functions.

  4. 4

    Beanie ODM for MongoDB

    intermediatestandard

    An asynchronous Python ODM for MongoDB based on Pydantic. It allows you to use the same models for database storage and API validation.

  5. 5

    Tortoise ORM

    beginnerstandard

    A Django-inspired async ORM built specifically for FastAPI. Ideal for developers who prefer an Active Record pattern over SQLAlchemy's Data Mapper pattern.

  6. 6

    Connection Pooling with asyncpg

    advancedhigh

    Optimize PostgreSQL performance by using asyncpg's connection pool directly for high-throughput read operations that don't require a full ORM.

  7. 7

    Database Transaction Middleware

    advancedstandard

    Implement a custom middleware to handle database transactions per request, ensuring automatic rollbacks on 4xx/5xx responses.

  8. 8

    Prisma Client Python

    intermediatemedium

    Use the Prisma ORM for auto-generated, type-safe database clients. It provides a superior developer experience for complex schema relationships.

  9. 9

    Piccolo ORM

    intermediatestandard

    An async ORM and query builder that includes a built-in admin interface and migration system, similar to Django but optimized for asyncio.

  10. 10

    Database Health Checks

    beginnerstandard

    Create a dedicated /health endpoint that pings the database and Redis to ensure the application is truly ready to receive traffic.

AI/LLM Integration and Streaming

  1. 1

    StreamingResponse for LLMs

    intermediatehigh

    Use fastapi.responses.StreamingResponse to stream tokens from OpenAI or local LLMs to the client in real-time, reducing perceived latency.

  2. 2

    LangServe Implementation

    intermediatehigh

    Deploy LangChain chains as FastAPI endpoints using LangServe. It automatically generates input/output schemas and provides a playground UI.

  3. 3

    SSEStarlette for Events

    advancedstandard

    Implement Server-Sent Events (SSE) using sse-starlette to push updates from long-running AI inference tasks back to the frontend.

  4. 4

    Ray Serve for Model Scaling

    advancedhigh

    Integrate Ray Serve with FastAPI to scale compute-intensive ML models across a cluster while maintaining a standard REST interface.

  5. 5

    FastAPI-Limiter for AI Quotas

    intermediatestandard

    Apply rate limiting to expensive AI endpoints using Redis-backed fastapi-limiter to prevent API abuse and manage inference costs.

  6. 6

    Asyncio Semaphore for Backpressure

    advancedhigh

    Use asyncio.Semaphore(n) to limit the number of concurrent requests to a GPU-bound model, preventing OOM (Out of Memory) errors.

  7. 7

    BentoML for Model Serving

    intermediatestandard

    Package models with BentoML and serve them via FastAPI. It handles model versioning and provides optimized runners for inference.

  8. 8

    Prometheus Monitoring for ML

    intermediatestandard

    Use prometheus-fastapi-instrumentator to track inference time, token usage, and model error rates for production AI services.

  9. 9

    BackgroundTasks for Pre-processing

    beginnerhigh

    Offload data cleaning or vector embedding generation to FastAPI's BackgroundTasks to return immediate 202 Accepted responses to users.

  10. 10

    vLLM Integration

    advancedhigh

    Connect FastAPI to a vLLM inference server for high-throughput LLM serving, utilizing PagedAttention for efficient memory management.

Security, Auth, and Deployment

  1. 1

    FastAPI Users for Auth

    intermediatehigh

    Implement the fastapi-users library for a complete authentication system including registration, JWT/Cookie strategy, and password reset.

  2. 2

    OAuth2 with Password Flow

    intermediatestandard

    Use FastAPI's built-in OAuth2PasswordBearer to implement secure token-based authentication without external providers.

  3. 3

    Uvicorn Gunicorn Worker Strategy

    intermediatehigh

    Deploy using Gunicorn with the Uvicorn worker class (uvicorn.workers.UvicornWorker) to manage multiple processes and improve reliability.

  4. 4

    Nginx Reverse Proxy Config

    intermediatestandard

    Configure Nginx with proxy_buffering off and proxy_set_header Connection 'upgrade' to support WebSockets and streaming responses.

  5. 5

    Pydantic Settings Management

    beginnerstandard

    Use pydantic-settings to manage environment variables. It provides automatic validation and type casting for configuration values.

  6. 6

    CORS Middleware Configuration

    beginnerstandard

    Properly configure CORSMiddleware with specific allow_origins instead of '*' to secure your API against cross-site request forgery.

  7. 7

    Pytest with AsyncClient

    intermediatehigh

    Write integration tests using httpx.AsyncClient and pytest-asyncio to simulate API requests in an asynchronous test environment.

  8. 8

    Docker Multi-stage Builds

    intermediatestandard

    Use multi-stage Dockerfiles to reduce image size by separating the build dependencies from the final production runtime environment.

  9. 9

    API Key Middleware

    beginnerstandard

    Implement simple API Key authentication for internal service-to-service communication using a custom Security dependency.

  10. 10

    OpenAPI Documentation Customization

    beginnerstandard

    Override the default Swagger UI settings in the FastAPI constructor to disable documentation in production or add custom branding.