FastAPI is a modern, high-performance Python web framework for building APIs based on standard Python type hints. It's built on top of Starlette for web handling and Pydantic for data validation, providing automatic API documentation, async support, and excellent developer experience. FastAPI excels at creating production-ready RESTful APIs quickly while maintaining type safety and performance. One key distinction: FastAPI's automatic validation and documentation generation from type hints eliminates boilerplate code that other frameworks require manually, making it both fast to develop with and fast to execute.
Quick Index
Mind Map
19 tables, 155 concepts. Select a concept node to jump to its table row.
Preparing mind map...
Table 1: Core Application Setup
| Concept | Example | Description |
|---|---|---|
app = FastAPI()app = FastAPI(title="My API", version="1.0.0") | • Creates the main application instance • accepts optional metadata like title, description, version for OpenAPI docs. | |
| • Defines an HTTP endpoint with method and path • decorator tells FastAPI to handle requests to this route. | |
def read_root(): return {"msg": "Hello"} | • Function executed when endpoint is hit • return value is automatically serialized to JSON. | |
fastapi dev main.pyfastapi run main.py | • Recommended way to run FastAPI (included in fastapi[standard])• dev for development (auto-reload, localhost only); run for production (no reload, 0.0.0.0). | |
uvicorn main:app --reload | • Starts the ASGI server directly; preferred for containerized or programmatic use • fastapi dev/fastapi run are now the recommended alternatives. | |
async def read_items(): return await db.fetch() | • Uses async def for non-blocking I/O operations• better performance for I/O-bound tasks. | |
from contextlib import asynccontextmanagerasync def lifespan(app): # startup yield # shutdownapp = FastAPI(lifespan=lifespan) | • Manages startup and shutdown logic • replaces deprecated on_event decorators with single context manager. | |
/docs for Swagger UI/redoc for ReDoc | • FastAPI auto-generates interactive API docs at these endpoints based on your code • requires zero configuration. | |
class Item(BaseModel): name: str price: float | • Pydantic models provide automatic validation and serialization • FastAPI uses them for request/response schemas. |
Table 2: HTTP Methods and Route Definitions
| Method | Example | Description |
|---|---|---|
def read_item(id: int): | • Retrieves data • no request body, typically uses path or query parameters. | |
def create_item(item: Item): | • Creates new resource • accepts request body defined by Pydantic model. | |
def update_item(id: int, item: Item): | • Replaces entire resource • expects complete object in request body. | |
def partial_update(id: int, item: PartialItem): | • Updates partial resource • only specified fields are modified. | |
def delete_item(id: int): | • Removes resource • typically returns status confirmation. | |
def items_head(): | • Returns headers only, no body • useful for checking resource existence or metadata. | |
def items_options(): | • Returns allowed HTTP methods for endpoint • often handled automatically for CORS. |
Table 3: Request Parameters
| Type | Example | Description |
|---|---|---|
from typing import Annotatedq: Annotated[str | None, Query(max_length=50)] = None | • Recommended modern syntax (since FastAPI 0.95.0) for declaring parameters with validation • keeps type annotation and metadata together. | |
def read(item_id: int): | • Extracts value from URL path • type validated automatically based on annotation. | |
def read_items(skip: int = 0, limit: int = 10): | • Reads from URL query string (?skip=0&limit=10)• optional with defaults. | |
def create(item: Item): | • Accepts JSON payload • Pydantic model validates structure and types automatically. | |
def create(item: Item, user: User): | • Accepts multiple JSON objects in request body • FastAPI expects nested structure. | |
from fastapi import Headerdef read(user_agent: str = Header()): | • Reads HTTP headers • automatically converts hyphen-case to snake_case. | |
from fastapi import Cookiedef read(session_id: str = Cookie()): | • Extracts cookie values • type-validated like other parameters. | |
from fastapi import Formdef login(username: str = Form()): | • Accepts application/x-www-form-urlencoded• requires python-multipart installed. | |
from fastapi import UploadFiledef upload(file: UploadFile): | • Handles file uploads • UploadFile provides async methods and metadata like filename. | |
def upload(files: list[UploadFile]): | • Accepts multiple files in single request • validated as list. |
Table 4: Parameter Validation
| Technique | Example | Description |
|---|---|---|
from typing import Annotatedq: Annotated[str | None, Query(min_length=3)] = None | • Recommended way to use Query, Path, Header, Cookie • type annotation and validation rules stay together. | |
from fastapi import Queryq: str = Query(min_length=3) | Applies constraints like min/max length, regex patterns to query parameters. | |
from fastapi import Pathid: int = Path(ge=1, le=1000) | Validates path parameters with numeric constraints like ge (greater/equal), le (less/equal). | |
q: Annotated[str, Query(min_length=1)] | • Modern approach: no default = required when using Annotated • older approach: q: str = Query(...) with ellipsis. | |
q: str | None = None | • Python 3.10+ union syntax for optional parameters • older versions use Optional[str]. | |
tags: list[str] = Query([]) | • Accepts multiple values for same parameter (?tags=a&tags=b)• validated as list. | |
item_query: str = Query(alias="item-query") | Maps hyphenated URL param to snake_case Python variable. | |
old_param: str = Query(deprecated=True) | • Marks parameter as deprecated in OpenAPI docs • still functional but discouraged. | |
code: str = Query(pattern="^[A-Z]{3}$") | Validates string parameter against regex pattern. | |
price: float = Query(gt=0, le=9999.99) | Applies gt (greater than), lt (less than), ge, le constraints to numbers. |
Table 5: Pydantic Models and Validation
| Concept | Example | Description |
|---|---|---|
class Item(BaseModel): name: str price: float | • Base class for all Pydantic models • provides automatic validation and serialization. | |
from pydantic import Fieldprice: float = Field(gt=0) | • Adds validation rules directly to model fields • similar to Query/Path but for models. | |
name: str = Field(description="Item name") | • Adds documentation to field • appears in OpenAPI schema. | |
price: float = Field(examples=[9.99, 19.99]) | Provides example values for API documentation and testing. | |
def check_email(cls, v): | • Custom validation logic for specific field • runs after type validation. | |
def check_passwords(self): | • Validates entire model after individual fields • useful for cross-field validation. | |
from pydantic import ConfigDictmodel_config = ConfigDict(str_strip_whitespace=True) | • Configures model behavior using Pydantic v2's ConfigDict• replaces the old inner class Config. | |
description: str | None = None | • Field can be omitted or null • uses Python union type or Optional. | |
def total(self) -> float: | • Adds calculated field to model • included in serialization but not validation. | |
class ExtendedItem(Item): category: str | • Inherits fields from base model • enables model reuse and extension. |
Table 6: Response Configuration
| Technique | Example | Description |
|---|---|---|
| • Specifies return type for validation and docs • filters response to match model. | |
async def create_item(item: Item) -> Item: | • Modern preferred approach for response type declaration • FastAPI uses the return annotation for validation, filtering, and docs. | |
response_model=User, response_model_exclude={"password"} | • Removes specified fields from response • useful for hiding sensitive data. | |
| • Sets HTTP status code for response • default is 200 for GET, 201 for POST recommended. | |
from fastapi.responses import JSONResponsereturn JSONResponse(content=data) | Explicit JSON response with custom headers or status code. | |
from fastapi.responses import HTMLResponsereturn HTMLResponse(content=html) | • Returns HTML content • sets Content-Type to text/html. | |
from fastapi.responses import RedirectResponsereturn RedirectResponse(url="/new") | • HTTP redirect to different URL • status_code defaults to 307. | |
from fastapi.responses import FileResponsereturn FileResponse(path="file.pdf") | • Serves static files • handles content-type and download headers automatically. | |
from fastapi.responses import StreamingResponsereturn StreamingResponse(generator) | • Streams large data in chunks • memory-efficient for big responses. | |
from fastapi.responses import ORJSONResponsereturn ORJSONResponse(content=data) | • Uses faster orjson library for JSON serialization • 2-3x performance improvement. | |
from fastapi import Responseresponse.headers["X-Custom"] = "value" | Sets custom HTTP headers in response. | |
response.set_cookie(key="session", value="abc") | • Adds cookie to response • supports httponly, secure, samesite options. |
Table 7: Dependency Injection
| Pattern | Example | Description |
|---|---|---|
from typing import Annotateddef route(db: Annotated[DB, Depends(get_db)]): | • Function providing reusable logic • recommended Annotated syntax (since 0.95.0) keeps type and dependency together. | |
DBDep = Annotated[Session, Depends(get_db)]def endpoint(db: DBDep): | • Defines reusable type alias for common dependency • reduces repetition across many routes. | |
async def get_session(): async with Session() as s: yield s | • Async generator dependency • cleanup happens after response using yield. | |
class Pagination: def __init__(self, skip=0): | • Class instances as dependencies • __init__ parameters become sub-dependencies. | |
def get_user(token = Depends(get_token)): | • Dependency can depend on other dependencies • creates dependency chain. | |
app = FastAPI(dependencies=[Depends(verify)]) | • Applied to all routes in application • useful for auth, logging. | |
router = APIRouter(dependencies=[Depends(check)]) | • Applied to all routes in router • scoped to specific module. | |
def get_db(): db = Database() yield db db.close() | • Provides resource cleanup after request • code after yield runs as teardown. | |
app.dependency_overrides[get_db] = mock_db | • Replaces dependency for testing • allows mocking without changing code. | |
| • Dependency executed but result not used in function • for side effects only. |
Table 8: Error Handling
| Approach | Example | Description |
|---|---|---|
from fastapi import HTTPExceptionraise HTTPException(status_code=404, detail="Not found") | • Built-in exception for HTTP errors • automatically formatted as JSON response. | |
class CustomError(Exception): pass | • Define custom exception class • can add custom handler. | |
def handler(request, exc): | • Catches specific exception type globally • returns custom response. | |
from fastapi.exceptions import RequestValidationError | Customizes Pydantic validation error response format. | |
raise HTTPException(status_code=403, detail="Forbidden") | • Sets HTTP status code directly in exception • common codes: 400, 401, 403, 404, 500. | |
raise HTTPException(status_code=401, headers={"WWW-Authenticate": "Bearer"}) | • Adds custom headers to error response • useful for auth challenges. | |
from starlette.exceptions import HTTPException as StarletteHTTPException | Replaces FastAPI's default error formatting. |
Table 9: Authentication and Security
| Mechanism | Example | Description |
|---|---|---|
from fastapi.security import OAuth2PasswordBeareroauth2 = OAuth2PasswordBearer(tokenUrl="token") | • Standard OAuth2 flow for password-based authentication • extracts token from Authorization header. | |
from fastapi.security import OAuth2PasswordRequestFormdef login(form: OAuth2PasswordRequestForm = Depends()): | • Form data model for username/password login • includes username, password, optional scope. | |
from fastapi.security import APIKeyHeaderapi_key = APIKeyHeader(name="X-API-Key") | • Extracts API key from custom header • name specifies header name. | |
from fastapi.security import APIKeyQueryapi_key = APIKeyQuery(name="api_key") | • Reads API key from query parameter • less secure than header. | |
from fastapi.security import APIKeyCookieapi_key = APIKeyCookie(name="session") | Extracts API key from cookie. | |
from jose import jwttoken = jwt.encode(data, SECRET, algorithm="HS256") | • Encodes JWT token with payload and secret • requires python-jose library. | |
from jose import JWTError, jwtpayload = jwt.decode(token, SECRET, algorithms=["HS256"]) | • Decodes and verifies JWT • raises JWTError if invalid. | |
from passlib.context import CryptContextpwd_context = CryptContext(schemes=["bcrypt"]) | • Hashes passwords with bcrypt • never store plain passwords. | |
async def get_current_user(token = Depends(oauth2)): # decode token, fetch user | • Dependency that extracts and validates user from token • reusable across routes. | |
| • Permission-based access control • validates OAuth2 scopes. |
Table 10: Middleware
| Type | Example | Description |
|---|---|---|
from fastapi.middleware.cors import CORSMiddlewareapp.add_middleware(CORSMiddleware, allow_origins=["*"]) | • Enables Cross-Origin Resource Sharing • configures which domains can access API. | |
async def add_header(request, call_next): | • Function-based middleware • runs before and after every request. | |
class TimingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): | • Class-based middleware • more complex logic, state management. | |
from starlette.middleware.trustedhost import TrustedHostMiddlewareapp.add_middleware(TrustedHostMiddleware, allowed_hosts=["*.example.com"]) | • Validates Host header • prevents HTTP Host header attacks. | |
from starlette.middleware.httpsredirect import HTTPSRedirectMiddlewareapp.add_middleware(HTTPSRedirectMiddleware) | • Redirects HTTP to HTTPS • enforces secure connections. | |
from fastapi.middleware.gzip import GZipMiddlewareapp.add_middleware(GZipMiddleware, minimum_size=1000) | • Compresses responses over specified size • reduces bandwidth. | |
from starlette.middleware.sessions import SessionMiddlewareapp.add_middleware(SessionMiddleware, secret_key="key") | Adds session support via signed cookies. |
Table 11: Background Tasks
| Approach | Example | Description |
|---|---|---|
from fastapi import BackgroundTasksdef task(email: str): send_email(email) | • Simple background function executed after response • no external queue needed. | |
def endpoint(bg: BackgroundTasks): bg.add_task(send_email, to="user@example.com") | • Schedules function to run after response sent • tasks run in same process. | |
bg.add_task(task1)bg.add_task(task2) | Multiple tasks run sequentially in order added. | |
def task(db = Depends(get_db)): | • Background task can use dependency injection • dependencies resolved when task runs. | |
from celery import Celerycelery = Celery("tasks", broker="redis://localhost")def heavy_task(): | • Distributed task queue for heavy/long-running jobs • runs in separate workers outside request cycle. | |
from arq import create_poolredis = await create_pool() | • Redis-based async task queue • alternative to Celery for async-first applications. |
Table 12: Database Integration
| Technique | Example | Description |
|---|---|---|
from sqlalchemy.ext.asyncio import AsyncSessionasync def get_db(): yield session | • Async database session for non-blocking DB operations • requires async driver. | |
from sqlalchemy.orm import Sessiondef get_db(): yield db | • Synchronous session • simpler but blocks during queries. | |
from sqlalchemy import Column, Integer, Stringclass User(Base): id = Column(Integer, primary_key=True) | • ORM model defining table structure • SQLAlchemy maps to database tables. | |
result = await session.execute(select(User))users = result.scalars().all() | • Executes async query • uses SQLAlchemy 2.0 style. | |
def endpoint(db: Session = Depends(get_db)): | • Injects database session into route • session closed automatically after request. | |
alembic init alembicalembic revision --autogeneratealembic upgrade head | • Database schema migrations • tracks and applies schema changes over time. | |
engine = create_async_engine(url, pool_size=20, max_overflow=10) | • Reuses database connections • critical for production performance. |
Table 13: WebSockets and Real-Time Communication
| Feature | Example | Description |
|---|---|---|
from fastapi import WebSocketasync def websocket_endpoint(websocket: WebSocket): | • Defines WebSocket route • full-duplex communication channel. | |
await websocket.accept() | • Establishes WebSocket connection • must be called before send/receive. | |
data = await websocket.receive_text()data = await websocket.receive_json() | • Reads message from client • supports text, JSON, or bytes. | |
await websocket.send_text("Hello")await websocket.send_json({"msg": "Hi"}) | Sends message to client. | |
try: while True: await websocket.receive_text()except WebSocketDisconnect: | • Handles client disconnect • exception raised when connection closes. | |
from fastapi.responses import StreamingResponsedef event_stream(): yield f"data: {msg}\n\n" | • One-way streaming from server to client • simpler than WebSockets for uni-directional updates. |
Table 14: Testing
| Tool | Example | Description |
|---|---|---|
from fastapi.testclient import TestClientclient = TestClient(app)response = client.get("/") | • Synchronous test client • tests FastAPI without running server. | |
def test_read_main(): response = client.get("/") assert response.status_code == 200 | • Standard pytest patterns work with TestClient • uses fixtures for setup. | |
with TestClient(app) as client: response = client.get("/") | • Triggers lifespan events during testing • startup/shutdown run automatically. | |
from httpx import AsyncClientasync with AsyncClient(app=app) as client: response = await client.get("/") | • Async testing with httpx • required for testing async dependencies properly. | |
app.dependency_overrides[get_db] = lambda: mock_db | • Replaces real dependency with mock for testing • no code changes needed. | |
files = {"file": ("test.txt", b"content", "text/plain")}client.post("/upload", files=files) | • Simulates file upload in tests • tuple format: (filename, content, content-type). | |
def client(): return TestClient(app) | • Reusable test setup • pytest fixture creates client for all tests. |
Table 15: Advanced Routing
| Concept | Example | Description |
|---|---|---|
from fastapi import APIRouterrouter = APIRouter(prefix="/items", tags=["items"]) | • Modular routing • groups related endpoints with shared prefix and tags. | |
app.include_router(router) | • Mounts router to main app • enables splitting large apps into modules. | |
app.mount("/v1", app_v1) | • Mounts independent FastAPI app at path • useful for API versioning. | |
from fastapi.staticfiles import StaticFilesapp.mount("/static", StaticFiles(directory="static")) | Serves static files from directory. | |
router = APIRouter(dependencies=[Depends(verify_token)]) | • Applies dependency to all routes in router • cleaner than per-route. | |
router = APIRouter(tags=["items"]) | • Groups endpoints in OpenAPI docs • creates collapsible sections. | |
Define more specific routes first: | • FastAPI matches first matching route • specific paths before parameterized ones. |
Table 16: OpenAPI Customization
| Element | Example | Description |
|---|---|---|
app = FastAPI(title="My API", description="Docs", version="1.0") | Sets API title, description, version in OpenAPI schema and docs. | |
tags_metadata = [{"name": "items", "description": "Item operations"}]app = FastAPI(openapi_tags=tags_metadata) | Adds descriptions to tag groups in documentation. | |
def custom_openapi(): # modify schemaapp.openapi = custom_openapi | • Overrides OpenAPI generation • add custom extensions or modify schema. | |
app = FastAPI(docs_url=None, redoc_url=None) | • Hides documentation endpoints • use in production if needed. | |
app = FastAPI(docs_url="/api/docs") | Changes Swagger UI path from default /docs. | |
| • Sets unique operation identifier in OpenAPI • useful for code generation tools. | |
| • Marks endpoint as deprecated in docs • still functional. | |
responses={200: {"description": "OK", "content": {"application/json": {"example": {...}}}}} | Adds example responses to OpenAPI docs. | |
app = FastAPI(separate_input_output_schemas=False) | • FastAPI 0.102.0+ generates separate OpenAPI schemas for input and output with Pydantic v2 • set False to disable. | |
app = FastAPI(swagger_ui_parameters={"defaultModelsExpandDepth": -1}) | Customizes Swagger UI behavior like theme, syntax highlighting, model expansion. |
Table 17: Settings and Configuration
| Technique | Example | Description |
|---|---|---|
from pydantic_settings import BaseSettingsclass Settings(BaseSettings): api_key: str | • Type-safe configuration from environment variables • validates config at startup. | |
from pydantic_settings import SettingsConfigDictmodel_config = SettingsConfigDict(env_file=".env") | • Loads environment variables from .env using Pydantic Settings v2 • replaces old inner class Config: env_file = ".env" pattern. | |
def get_settings(): return Settings()settings: Settings = Depends(get_settings) | • Injects settings into routes • enables easy mocking in tests. | |
def get_settings(): return Settings() | • Loads settings once and caches • improves performance. | |
class Settings(BaseSettings): env: str = "dev" database_url: str | • Uses different config per environment • set via ENV variable. |
Table 18: Performance Optimization
| Strategy | Example | Description |
|---|---|---|
async def fetch_data(): return await http_client.get(url) | • Use async def for I/O-bound operations• enables concurrent request handling. | |
from fastapi_cache import FastAPICachefrom fastapi_cache.backends.redis import RedisBackend | • Caches responses in Redis • reduces database load for repeated queries. | |
| • Sets HTTP caching headers • clients/proxies cache responses. | |
engine = create_engine(url, pool_size=20) | • Reuses database connections • critical for high-throughput APIs. | |
app = FastAPI(default_response_class=ORJSONResponse) | • Uses faster JSON library • 2-3x performance improvement over standard json. | |
uvicorn main:app --workers 4 | • Runs multiple worker processes • utilizes multiple CPU cores. | |
gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker | • Process manager with Uvicorn workers • production-grade deployment. | |
FROM python:3.14RUN pip install fastapi[standard]CMD ["fastapi", "run", "main.py", "--port", "80"] | • Official Docker image pattern for FastAPI production deployment • uses fastapi run included in fastapi[standard]. |
Table 19: Advanced Patterns
| Pattern | Example | Description |
|---|---|---|
from strawberry.fastapi import GraphQLRouterapp.include_router(GraphQLRouter(schema), prefix="/graphql") | • Adds GraphQL endpoint using Strawberry • enables flexible query language. | |
from slowapi import Limiterdef endpoint(): | • Throttles requests per IP/user • prevents API abuse. | |
app.mount("/v1", v1_app)app.mount("/v2", v2_app) | • Versions API via URL path • most common versioning strategy. | |
version = request.headers.get("API-Version", "v1") | • Reads version from custom header • cleaner URLs but less discoverable. | |
from fastapi_utils.cbv import cbvclass ItemAPI: | • Groups related endpoints in class • reduces boilerplate for CRUD operations. | |
from msgpack_asgi import MessagePackMiddlewareapp.add_middleware(MessagePackMiddleware) | • Uses binary format for smaller payloads • faster than JSON for large data. | |
async def add_request_id(request, call_next): | • Adds unique ID to each request • enables distributed tracing. |
References
Official Documentation
- FastAPI Official Documentation - https://fastapi.tiangolo.com/
- FastAPI Tutorial - User Guide - https://fastapi.tiangolo.com/tutorial/
- FastAPI First Steps - https://fastapi.tiangolo.com/tutorial/first-steps/
- FastAPI Path Parameters - https://fastapi.tiangolo.com/tutorial/path-params/
- FastAPI Query Parameters - https://fastapi.tiangolo.com/tutorial/query-params/
- FastAPI Request Body - https://fastapi.tiangolo.com/tutorial/body/
- FastAPI Query Parameters and String Validations - https://fastapi.tiangolo.com/tutorial/query-params-str-validations/
- FastAPI Path Parameters Numeric Validations - https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/
- FastAPI Header Parameters - https://fastapi.tiangolo.com/tutorial/header-params/
- FastAPI Cookie Parameters - https://fastapi.tiangolo.com/tutorial/cookie-params/
- FastAPI Request Forms - https://fastapi.tiangolo.com/tutorial/request-forms/
- FastAPI Request Files - https://fastapi.tiangolo.com/tutorial/request-files/
- FastAPI Handling Errors - https://fastapi.tiangolo.com/tutorial/handling-errors/
- FastAPI Response Model - https://fastapi.tiangolo.com/tutorial/response-model/
- FastAPI Response Status Code - https://fastapi.tiangolo.com/tutorial/response-status-code/
- FastAPI Dependencies - https://fastapi.tiangolo.com/tutorial/dependencies/
- FastAPI Security - OAuth2 with Password and Bearer - https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/
- FastAPI Background Tasks - https://fastapi.tiangolo.com/tutorial/background-tasks/
- FastAPI Metadata and Docs URLs - https://fastapi.tiangolo.com/tutorial/metadata/
- FastAPI Bigger Applications - APIRouter - https://fastapi.tiangolo.com/tutorial/bigger-applications/
- FastAPI CORS - https://fastapi.tiangolo.com/tutorial/cors/
- FastAPI SQL Databases - https://fastapi.tiangolo.com/tutorial/sql-databases/
- FastAPI Testing - https://fastapi.tiangolo.com/tutorial/testing/
- FastAPI Async / Await - https://fastapi.tiangolo.com/async/
- FastAPI Advanced Dependencies - https://fastapi.tiangolo.com/advanced/advanced-dependencies/
- FastAPI Custom Response - https://fastapi.tiangolo.com/advanced/custom-response/
- FastAPI Response Headers - https://fastapi.tiangolo.com/advanced/response-headers/
- FastAPI Response Cookies - https://fastapi.tiangolo.com/advanced/response-cookies/
- FastAPI Settings and Environment Variables - https://fastapi.tiangolo.com/advanced/settings/
- FastAPI Sub Applications - https://fastapi.tiangolo.com/advanced/sub-applications/
- FastAPI Middleware - https://fastapi.tiangolo.com/advanced/middleware/
- FastAPI WebSockets - https://fastapi.tiangolo.com/advanced/websockets/
- FastAPI Lifespan Events - https://fastapi.tiangolo.com/advanced/events/
- FastAPI Testing Events - https://fastapi.tiangolo.com/advanced/testing-events/
- FastAPI Testing Dependencies - https://fastapi.tiangolo.com/advanced/testing-dependencies/
- FastAPI Extending OpenAPI - https://fastapi.tiangolo.com/how-to/extending-openapi/
- FastAPI Configure Swagger UI - https://fastapi.tiangolo.com/how-to/configure-swagger-ui/
- FastAPI GraphQL - https://fastapi.tiangolo.com/how-to/graphql/
- FastAPI Reference - FastAPI class - https://fastapi.tiangolo.com/reference/fastapi/
- FastAPI Reference - APIRouter - https://fastapi.tiangolo.com/reference/apirouter/
- FastAPI Reference - Request Parameters - https://fastapi.tiangolo.com/reference/parameters/
- FastAPI Reference - Response Classes - https://fastapi.tiangolo.com/reference/responses/
Pydantic Documentation
- Pydantic Models - https://docs.pydantic.dev/latest/concepts/models/
- Pydantic Fields - https://docs.pydantic.dev/latest/concepts/fields/
- Pydantic Validators - https://docs.pydantic.dev/latest/concepts/validators/
- Pydantic Config - https://docs.pydantic.dev/latest/concepts/config/
- Pydantic Settings - https://docs.pydantic.dev/latest/concepts/pydantic_settings/
SQLAlchemy Documentation
- SQLAlchemy Async I/O - https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html
- SQLAlchemy Connection Pooling - https://docs.sqlalchemy.org/en/20/core/pooling.html
- Alembic Documentation - https://alembic.sqlalchemy.org/en/latest/
Starlette Documentation
- Starlette Middleware - https://www.starlette.io/middleware/
- Starlette TestClient - https://www.starlette.io/testclient/
Uvicorn Documentation
- Uvicorn Deployment - https://www.uvicorn.org/deployment/
Technical Blogs & Tutorials
- Real Python - Get Started With FastAPI - https://realpython.com/get-started-with-fastapi/
- Real Python - A Close Look at a FastAPI Example Application - https://realpython.com/fastapi-python-web-apis/
- TestDriven.io - Developing an API with FastAPI and GraphQL - https://testdriven.io/blog/fastapi-graphql/
- TestDriven.io - The Definitive Guide to Celery and FastAPI - https://testdriven.io/courses/fastapi-celery/intro/
- TestDriven.io - Developing a Real-time Dashboard with FastAPI, Postgres, and WebSockets - https://testdriven.io/blog/fastapi-postgres-websockets/
- Medium - Building a GraphQL Service with FastAPI & Strawberry - https://medium.com/@priyansu011/berry-sweet-apis-building-a-graphql-service-with-fastapi-strawberry-eb3b38efa143
- Medium - FastAPI + SQLAlchemy 2.0: Modern Async Database Patterns - https://dev-faizan.medium.com/fastapi-sqlalchemy-2-0-modern-async-database-patterns-7879d39b6843
- Medium - Redis Hybrid Caching in FastAPI - https://medium.com/@kirant3ja/redis-hybrid-caching-in-fastapi-af0bf0ec40cb
- Medium - Supercharging FastAPI with Celery - https://medium.com/algomart/supercharging-fastapi-with-celery-a-step-by-step-production-ready-guide-df3e983e04d6
- Medium - FastAPI Lifespan Explained - https://medium.com/algomart/fastapi-lifespan-explained-the-right-way-to-handle-startup-and-shutdown-logic-f825f38dd304
- Medium - Background Tasks in FastAPI - https://medium.com/algomart/background-tasks-in-fastapi-doing-more-without-making-users-wait-1b3febef50b4
- Medium - Testing FastAPI Application with Pytest - https://medium.com/@gnetkov/testing-fastapi-application-with-pytest-57080960fd62
- Medium - Exception Handling Best Practices in Python: A FastAPI Perspective - https://medium.com/delivus/exception-handling-best-practices-in-python-a-fastapi-perspective-98ede2256870
- Medium - Dependency Injection in Python, Beyond FastAPI's Depends - https://medium.com/@guillaume.launay/dependency-injection-in-python-beyond-fastapis-depends-eec237b1327b
- Medium - ORJSON + FastAPI - https://oandersonbm.medium.com/orjson-fastapi-a4477de3c3fc
- Medium - A Practical Guide to using Pydantic - https://medium.com/@marcnealer/a-practical-guide-to-using-pydantic-8aafa7feebf6
- Medium - FastAPI Real-Time API: WebSockets vs SSE vs Long-Polling (2026 Guide) - https://medium.com/@rameshkannanyt0078/fastapi-real-time-api-websockets-vs-sse-vs-long-polling-2026-guide-ce1029e4432e
- Medium - Building Real-Time Notifications with FastAPI in 2026 - https://medium.com/@sherrywalker01/building-real-time-notifications-with-fastapi-in-2026-953c9e8dd535
- Medium - Built a FastAPI Backend for AI Agents in 2026 - https://medium.com/@rameshkannanyt0078/built-a-fastapi-backend-for-ai-agents-in-2026-heres-what-broke-fa6c5b4d2c25
- Medium - FastAPI + Redis: Real-Time Caching & Rate Limiting - https://medium.com/@rameshkannanyt0078/fastapi-redis-real-time-caching-rate-limiting-for-production-apis-5b9b1bf08785
- Medium - Using SlowAPI in FastAPI: Mastering Rate Limiting Like a Pro - https://shiladityamajumder.medium.com/using-slowapi-in-fastapi-mastering-rate-limiting-like-a-pro-19044cb6062b
- David Muraya - A Guide to Authentication in FastAPI with JWT - https://davidmuraya.com/blog/fastapi-jwt-authentication/
- David Muraya - How to Handle File Uploads in FastAPI - https://davidmuraya.com/blog/fastapi-file-uploads/
- David Muraya - Blocked by CORS in FastAPI? Here's How to Fix It - https://davidmuraya.com/blog/fastapi-cors-configuration/
- David Muraya - Centralizing FastAPI Configuration with Pydantic Settings - https://davidmuraya.com/blog/centralizing-fastapi-configuration-with-pydantic-settings-and-env-files/
- David Muraya - Managing Background Tasks in FastAPI: BackgroundTasks vs ARQ - https://davidmuraya.com/blog/fastapi-background-tasks-arq-vs-built-in/
- David Muraya - FastAPI Tutorial: A Complete Guide for Beginners - https://davidmuraya.com/blog/fastapi-tutorial-for-beginners/
- Towards Data Science - Validations in Pydantic V2 - https://towardsdatascience.com/validations-in-pydantic-v2-15bcbb39a98b/
- Towards Data Science - Understanding When and How to Implement FastAPI Middleware - https://towardsdatascience.com/understanding-when-and-how-to-implement-fastapi-middleware-examples-and-use-cases-c2bd37cb4ffe/
- Towards Data Science - Introducing Server-Sent Events in Python - https://towardsdatascience.com/introducing-server-sent-events-in-python/
- Towards AI - II. Type Hints & Pydantic: FastAPI's Foundation - https://pub.towardsai.net/ii-type-hints-pydantic-fastapis-foundation-dcccba337eaf
- Towards AI - Building Production-Ready APIs with FastAPI, SQLAlchemy, and Alembic - https://pub.towardsai.net/building-production-ready-apis-with-fastapi-sqlalchemy-and-alembic-a-complete-guide-a4656b7e700c
- Python Plain English - Pydantic v2.10 Python Tutorial: Typed Settings for FastAPI - https://python.plainenglish.io/pydantic-v2-10-python-tutorial-typed-settings-for-fastapi-env-variables-docker-secrets-4bae378cb379
- Python Plain English - Automated API Documentation: Advanced OpenAPI Customizations in FastAPI - https://python.plainenglish.io/automated-api-documentation-advanced-openapi-customizations-in-fastapi-2df4024f3882
- Python Plain English - Real-Time Features in FastAPI: WebSockets, Event Streaming - https://python.plainenglish.io/real-time-features-in-fastapi-websockets-event-streaming-and-push-notifications-fec79a0a6812
- Python Plain English - Handling Background Tasks and Long-Running Jobs in FastAPI - https://python.plainenglish.io/handling-background-tasks-and-long-running-jobs-in-fastapi-the-complete-guide-b197d38145d7
- Python Plain English - Caching Strategies for FastAPI: Redis, In-Memory, and HTTP Cache Headers - https://python.plainenglish.io/caching-strategies-for-fastapi-redis-in-memory-and-http-cache-headers-8c7ba5d78666
- Python Plain English - API Rate Limiting and Abuse Prevention at Scale - https://python.plainenglish.io/api-rate-limiting-and-abuse-prevention-at-scale-best-practices-with-fastapi-b5d31d690208
- Hrekov - Advanced FastAPI Dependency Injection for Experts - https://hrekov.com/blog/advanced-fastapi-dependency-injection
- Honeybadger - FastAPI Error Handling: Types, Methods, and Best Practices - https://www.honeybadger.io/blog/fastapi-error-handling/
- Better Stack - FastAPI Error Handling Patterns - https://betterstack.com/community/guides/scaling-python/error-handling-fastapi/
- Semaphore CI - Building Custom Middleware in FastAPI - https://semaphore.io/blog/custom-middleware-fastapi
- Auth0 - FastAPI Best Practices - https://auth0.com/blog/fastapi-best-practices/
- Leapcell - Understanding Pitfalls of Async Task Management in FastAPI - https://leapcell.io/blog/understanding-pitfalls-of-async-task-management-in-fastapi-requests
- Leapcell - Revisiting Class-Based vs. Function-Based Views in Python Web Frameworks - https://leapcell.io/blog/revisiting-class-based-vs-function-based-views-in-python-web-frameworks-2025
- Leapcell - Understanding the Pillars of FastAPI Through Starlette - https://leapcell.io/blog/understanding-the-pillars-of-fastapi-through-starlette
- Christophergs - The Ultimate FastAPI Tutorial Part 8 - Project Structure and API Versioning - https://christophergs.com/tutorials/ultimate-fastapi-tutorial-pt-8-project-structure-api-versioning/
OneUptime Blog Series
- OneUptime - How to Use SQLAlchemy with FastAPI - https://oneuptime.com/blog/post/2026-01-27-sqlalchemy-fastapi/view
- OneUptime - How to Build REST APIs with FastAPI and SQLAlchemy - https://oneuptime.com/blog/post/2026-01-25-fastapi-sqlalchemy-rest-apis/view
- OneUptime - How to Build Background Task Processing in FastAPI - https://oneuptime.com/blog/post/2026-01-25-background-task-processing-fastapi/view
- OneUptime - How to Build Authentication Middleware in FastAPI - https://oneuptime.com/blog/post/2026-01-25-fastapi-authentication-middleware/view
- OneUptime - How to Build Production-Ready FastAPI Applications - https://oneuptime.com/blog/post/2026-01-27-fastapi-production-ready/view
- OneUptime - How to Implement File Uploads in FastAPI - https://oneuptime.com/blog/post/2026-01-26-fastapi-file-uploads/view
- OneUptime - How to Build Exception Handlers in FastAPI - https://oneuptime.com/blog/post/2026-01-24-exception-handlers-fastapi/view
- OneUptime - How to Fix 'API Versioning' Compatibility Issues - https://oneuptime.com/blog/post/2026-01-24-fix-api-versioning-compatibility-issues/view
- OneUptime - How to Implement Rate Limiting in FastAPI Without External Services - https://oneuptime.com/blog/post/2025-01-06-fastapi-rate-limiting/view
- OneUptime - How to Validate Data with Pydantic v2 Models - https://oneuptime.com/blog/post/2026-01-21-python-pydantic-v2-validation/view
- OneUptime - How to Implement Response Caching with Redis in Python - https://oneuptime.com/blog/post/2026-01-22-response-caching-redis-python/view
- OneUptime - How to Use Uvicorn for Production Deployments - https://oneuptime.com/blog/post/2026-02-03-python-uvicorn-production/view
- OneUptime - How to Add Middleware to FastAPI - https://oneuptime.com/blog/post/2026-02-02-fastapi-middleware/view
- OneUptime - How to Use Dependency Injection in FastAPI - https://oneuptime.com/blog/post/2026-02-02-fastapi-dependency-injection/view
- OneUptime - How to Handle Exceptions Globally in FastAPI - https://oneuptime.com/blog/post/2026-02-02-fastapi-global-exception-handling/view
- OneUptime - How to Generate OpenAPI Documentation in FastAPI - https://oneuptime.com/blog/post/2026-02-02-fastapi-openapi-documentation/view
- OneUptime - How to Deploy FastAPI to Production - https://oneuptime.com/blog/post/2026-02-02-fastapi-production-deployment/view
- OneUptime - How to Implement Background Tasks in FastAPI - https://oneuptime.com/blog/post/2026-02-02-fastapi-background-tasks/view
- OneUptime - How to Implement Custom Middleware in FastAPI - https://oneuptime.com/blog/post/2026-02-03-fastapi-custom-middleware/view
- OneUptime - How to Build a WebSocket Streaming API with FastAPI and Azure Web PubSub - https://oneuptime.com/blog/post/2026-02-16-how-to-build-a-websocket-streaming-api-with-fastapi-and-azure-web-pubsub/view
- OneUptime - How to Build a GraphQL API with Strawberry in Python - https://oneuptime.com/blog/post/2026-02-16-how-to-build-a-graphql-api-with-strawberry-in-python-and-deploy-to-azure-app-service/view
Additional Resources
- Strawberry GraphQL - FastAPI Integration - https://strawberry.rocks/docs/integrations/fastapi
- FastAPI Utilities - Class Based Views - https://fastapi-utils.davidmontague.xyz/user-guide/class-based-views/
- Speakeasy - How To Generate an OpenAPI Document With FastAPI - https://www.speakeasy.com/openapi/frameworks/fastapi
- Speakeasy - Responses Best Practices in REST API Design - https://www.speakeasy.com/api-design/responses
- Speakeasy - HTTP Methods Best Practices in REST API Design - https://www.speakeasy.com/api-design/http-methods
- WorkOS - Top 5 authentication solutions for secure FastAPI apps in 2026 - https://workos.com/blog/top-authentication-solutions-fastapi-2026
- WorkOS - Building authentication in Python web applications - https://workos.com/blog/python-authentication-guide-2026
- Visual Studio Code - FastAPI Tutorial in Visual Studio Code - https://code.visualstudio.com/docs/python/tutorial-fastapi
- Codecademy - Build a FastAPI-Powered API with Python in Minutes - https://www.codecademy.com/article/build-a-fast-api-powered-api-with-python-in-minutes
- Mindbowser - FastAPI Data Validation with Pydantic Explained - https://www.mindbowser.com/fastapi-data-validation-pydantic/
- Escape.tech - How to secure APIs built with FastAPI: A complete guide - https://escape.tech/blog/how-to-secure-fastapi-api/
- InfoWorld - Get started with FastAPI - https://www.infoworld.com/article/2268623/get-started-with-fastapi.html
- Render - FastAPI production deployment best practices - https://render.com/articles/fastapi-production-deployment-best-practices
- Blueshoe - FastAPI in Production: Here's How It Works! - https://www.blueshoe.io/blog/fastapi-in-production/
- ZestMinds - FastAPI Deployment Guide for 2026 - https://www.zestminds.com/blog/fastapi-deployment-guide/
- ZestMinds - FastAPI Python Version Requirements & Setup (2026 Guide) - https://www.zestminds.com/blog/fastapi-requirements-setup-guide-2025/
- Seenode - Production-Ready FastAPI Deployment Using Docker and Uvicorn - https://seenode.com/blog/deploy-fastapi-docker-and-uvicorn
- KnowledgeLib - API Versioning Strategies: URL Path, Header, Query - https://knowledgelib.io/software/patterns/api-versioning/2026
- Pysquad - Beyond Basic Caching: Advanced Strategies with FastAPI - https://pysquad.com/blogs/beyond-basic-caching-advanced-strategies-with-fast
- Fast.io - API Caching Strategies with Redis - 2026 Guide - https://fast.io/resources/fastio-api-caching-strategies-redis/
- Levo.ai - API Rate Limiting 2026 | How It Works & Why It Matters - https://www.levo.ai/resources/blogs/api-rate-limiting-guide-2026
- Chanhle.dev - Authentication in FastAPI: Complete Guide to JWT & OAuth2 - https://www.chanhle.dev/blog/authentication-in-fastapi-jwt-oauth2
- DevRiazul - Build High-Performance Python APIs in 2026 - https://devriazul.com/fastapi-complete-guide-build-high-performance-python-apis-2026
- Greeden Blog - FastAPI Performance Tuning & Caching Strategy 101 - https://blog.greeden.me/en/2026/02/03/fastapi-performance-tuning-caching-strategy-101-a-practical-recipe-for-growing-a-slow-api-into-a-lightweight-fast-api/
- Greeden Blog - The Complete FastAPI × pytest Guide - https://blog.greeden.me/en/2026/01/06/the-complete-fastapi-x-pytest-guide-building-fearless-to-change-apis-with-unit-tests-api-tests-integration-tests-and-mocking-strategies/
- Greeden Blog - FastAPI OpenAPI Power Techniques - https://blog.greeden.me/en/2026/02/17/fastapi-openapi-power-techniques-evolving-swagger-ui-into-a-living-api-specification-versioning-error-design-pagination-and-more/
- MojoAuth - Implement Caching with FastAPI - https://mojoauth.com/implement-caching/implement-caching-with-fastapi
- MojoAuth - Serialize and Deserialize MessagePack with FastAPI - https://mojoauth.com/serialize-and-deserialize/serialize-and-deserialize-messagepack-with-fastapi
- SSOJet - Serialize and Deserialize MessagePack in FastAPI - https://ssojet.com/serialize-and-deserialize/serialize-and-deserialize-messagepack-in-fastapi
Video Resources
- YouTube - Python FastAPI Tutorial (Part 1): Getting Started - https://www.youtube.com/watch?v=7AMjmCTumuo
- YouTube - Python FastAPI Tutorial (Part 4): Pydantic Schemas - https://www.youtube.com/watch?v=9GHxnttXxrA
- YouTube - Python FastAPI Tutorial (Part 5): Adding a Database - https://www.youtube.com/watch?v=NvOV3ig2tGY
- YouTube - Python FastAPI Tutorial (Part 6): Completing CRUD - https://www.youtube.com/watch?v=VyoGAoxQhxM
- YouTube - FastAPI Tutorial for Beginners – Full Course - https://www.youtube.com/watch?v=VirndPTeRaw
- YouTube - How to work with Environment variables and Configuration Files in FastAPI - https://www.youtube.com/watch?v=TI1jU2YbIPA
- YouTube - Streaming in React the Simple Way: Server-Sent Events (with FastAPI) - https://www.youtube.com/watch?v=hOAAg1WaZh8
- YouTube - Swagger Docs - The Ultimate Guide to Professional API (Part 6) - https://www.youtube.com/watch?v=0JDQ6y297RE
GitHub Repositories
- GitHub - seapagan/fastapi_async_sqlalchemy2_example - https://github.com/seapagan/fastapi_async_sqlalchemy2_example
- GitHub - strawberry-graphql/strawberry - https://github.com/strawberry-graphql/strawberry/discussions/1863
- GitHub - egoan82/fastapi-with-redis-as-cache - https://github.com/egoan82/fastapi-with-redis-as-cache
- GitHub - darixsamani/fastapi-rate-limiter - https://github.com/darixsamani/fastapi-rate-limiter
- GitHub - dmontagu/fastapi-utils - https://github.com/dmontagu/fastapi-utils/blob/master/fastapi_utils/cbv.py
FastAPI New Features
- FastAPI CLI - https://fastapi.tiangolo.com/fastapi-cli/
- FastAPI Separate OpenAPI Schemas - https://fastapi.tiangolo.com/how-to/separate-openapi-schemas/
- FastAPI Docker Deployment - https://fastapi.tiangolo.com/deployment/docker/
- FastAPI Generate Clients - https://fastapi.tiangolo.com/advanced/generate-clients/