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
Full Stack FastAPI Template
intermediatehighThe 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
FastAPI Best Practices Repository
beginnerstandardA curated list of architectural patterns on GitHub (zhanymkanov/fastapi-best-practices) covering folder structure, dependency injection, and centralized exception handling.
- 3
SQLModel Integration
intermediatehighUse SQLModel to eliminate code duplication between Pydantic models and SQLAlchemy entities. This reduces the surface area for bugs in larger applications.
- 4
Modular APIRouter Implementation
beginnerstandardBreak 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
FastAPI Versioning
intermediatestandardImplement 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
Dependency Injection for Service Layers
intermediatehighMove 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
Pydantic v2 Migration
intermediatehighUpgrade 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
FastAPI Pagination
beginnerstandardStandardize list responses using the fastapi-pagination library. It supports multiple backends including SQLAlchemy, Tortoise, and Motor with minimal boilerplate.
- 9
Custom Exception Handlers
beginnerstandardRegister global exception handlers using @app.exception_handler to return standardized JSON error schemas across the entire API.
- 10
Cookiecutter FastAPI
beginnerstandardA 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
SQLAlchemy 2.0 Async Session
advancedhighImplement the async version of SQLAlchemy's sessionmaker. Use the async_scoped_session for thread-safe operations in high-concurrency environments.
- 2
Alembic Async Migrations
intermediatestandardConfigure Alembic to use the async driver (e.g., postgresql+asyncpg). Modify the env.py file to use run_async for database schema updates.
- 3
Redis for Response Caching
intermediatehighIntegrate redis-py (async) to cache expensive database queries. Use the fastapi-cache2 library to implement easy decorator-based caching on path functions.
- 4
Beanie ODM for MongoDB
intermediatestandardAn asynchronous Python ODM for MongoDB based on Pydantic. It allows you to use the same models for database storage and API validation.
- 5
Tortoise ORM
beginnerstandardA Django-inspired async ORM built specifically for FastAPI. Ideal for developers who prefer an Active Record pattern over SQLAlchemy's Data Mapper pattern.
- 6
Connection Pooling with asyncpg
advancedhighOptimize PostgreSQL performance by using asyncpg's connection pool directly for high-throughput read operations that don't require a full ORM.
- 7
Database Transaction Middleware
advancedstandardImplement a custom middleware to handle database transactions per request, ensuring automatic rollbacks on 4xx/5xx responses.
- 8
Prisma Client Python
intermediatemediumUse the Prisma ORM for auto-generated, type-safe database clients. It provides a superior developer experience for complex schema relationships.
- 9
Piccolo ORM
intermediatestandardAn async ORM and query builder that includes a built-in admin interface and migration system, similar to Django but optimized for asyncio.
- 10
Database Health Checks
beginnerstandardCreate 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
StreamingResponse for LLMs
intermediatehighUse fastapi.responses.StreamingResponse to stream tokens from OpenAI or local LLMs to the client in real-time, reducing perceived latency.
- 2
LangServe Implementation
intermediatehighDeploy LangChain chains as FastAPI endpoints using LangServe. It automatically generates input/output schemas and provides a playground UI.
- 3
SSEStarlette for Events
advancedstandardImplement Server-Sent Events (SSE) using sse-starlette to push updates from long-running AI inference tasks back to the frontend.
- 4
Ray Serve for Model Scaling
advancedhighIntegrate Ray Serve with FastAPI to scale compute-intensive ML models across a cluster while maintaining a standard REST interface.
- 5
FastAPI-Limiter for AI Quotas
intermediatestandardApply rate limiting to expensive AI endpoints using Redis-backed fastapi-limiter to prevent API abuse and manage inference costs.
- 6
Asyncio Semaphore for Backpressure
advancedhighUse asyncio.Semaphore(n) to limit the number of concurrent requests to a GPU-bound model, preventing OOM (Out of Memory) errors.
- 7
BentoML for Model Serving
intermediatestandardPackage models with BentoML and serve them via FastAPI. It handles model versioning and provides optimized runners for inference.
- 8
Prometheus Monitoring for ML
intermediatestandardUse prometheus-fastapi-instrumentator to track inference time, token usage, and model error rates for production AI services.
- 9
BackgroundTasks for Pre-processing
beginnerhighOffload data cleaning or vector embedding generation to FastAPI's BackgroundTasks to return immediate 202 Accepted responses to users.
- 10
vLLM Integration
advancedhighConnect FastAPI to a vLLM inference server for high-throughput LLM serving, utilizing PagedAttention for efficient memory management.
Security, Auth, and Deployment
- 1
FastAPI Users for Auth
intermediatehighImplement the fastapi-users library for a complete authentication system including registration, JWT/Cookie strategy, and password reset.
- 2
OAuth2 with Password Flow
intermediatestandardUse FastAPI's built-in OAuth2PasswordBearer to implement secure token-based authentication without external providers.
- 3
Uvicorn Gunicorn Worker Strategy
intermediatehighDeploy using Gunicorn with the Uvicorn worker class (uvicorn.workers.UvicornWorker) to manage multiple processes and improve reliability.
- 4
Nginx Reverse Proxy Config
intermediatestandardConfigure Nginx with proxy_buffering off and proxy_set_header Connection 'upgrade' to support WebSockets and streaming responses.
- 5
Pydantic Settings Management
beginnerstandardUse pydantic-settings to manage environment variables. It provides automatic validation and type casting for configuration values.
- 6
CORS Middleware Configuration
beginnerstandardProperly configure CORSMiddleware with specific allow_origins instead of '*' to secure your API against cross-site request forgery.
- 7
Pytest with AsyncClient
intermediatehighWrite integration tests using httpx.AsyncClient and pytest-asyncio to simulate API requests in an asynchronous test environment.
- 8
Docker Multi-stage Builds
intermediatestandardUse multi-stage Dockerfiles to reduce image size by separating the build dependencies from the final production runtime environment.
- 9
API Key Middleware
beginnerstandardImplement simple API Key authentication for internal service-to-service communication using a custom Security dependency.
- 10
OpenAPI Documentation Customization
beginnerstandardOverride the default Swagger UI settings in the FastAPI constructor to disable documentation in production or add custom branding.