All bites
The whole library, newest first. Filter by what you are here for, or pick a topic if you already know.
8664 bites
Page 12
selectinload vs joinedload for eager loading
Use eager loading options to avoid lazy N+1; joinedload uses a single JOIN (good for many-to-one) but can fan out rows on collections; selectinload issues a second IN query (better for one-to-many).

Customizing FastAPI's Swagger UI Behavior
Treat FastAPI's Swagger UI as a configurable frontend, not a static page. You can customize its behavior by passing a dictionary of settings on app startup. This is useful for changing themes or pre-filling auth fields. The footgun: keys must be camelCase.
OAuth2 social login with your own JWT
A login endpoint redirects to the provider with a state param, a callback exchanges the code for the provider token, you fetch the user profile, upsert the local user, then mint your own JWT.

FastAPI Behind a Reverse Proxy: Fixing Docs URLs
A reverse proxy can hide the full URL from your FastAPI app, breaking OpenAPI docs. Tell your app about the proxy's path prefix by setting the root_path during initialization to ensure all generated URLs are correct.
Reading the full response body in middleware
Responses stream as multiple body messages and headers go first, so you cannot add a header after seeing the body; you must buffer all chunks, compute the hash, set the header, then resend.
Choosing Uvicorn worker count in production
Workers exist to use multiple CPU cores past the GIL; a common starting point ties count to cores, then you tune by load testing, balancing CPU and memory (each worker is a full copy) against connection-pool…
FastAPI Lifespan: Code Before Startup, After Shutdown
FastAPI's lifespan events are "open for business" and "closing time" routines that run once before startup and after shutdown. Use them to initialize a DB pool or load a model. The footgun is putting request-specific logic here; it runs once only.
FastAPI's WebSocket State Machine
FastAPI manages WebSockets with a state machine, tracking client and application states separately. You must explicitly accept() a connection before communicating. This is key for chat or notification features.
Your First Python Dockerfile Blueprint
A Dockerfile is a recipe for building a self-contained environment for your Python app. Use it to ensure your app runs identically everywhere, from your laptop to production. The common footgun is forgetting a .dockerignore file, which bloats your image.
From Dev Server to Production: Running FastAPI with Workers
Your dev server is a single process. For production, you need a process manager to run multiple Uvicorn worker processes, handling concurrent requests and providing fault tolerance.

Mangum: Run Python ASGI Apps on Serverless
Mangum is an adapter for running Python ASGI apps (like FastAPI) on serverless platforms like AWS Lambda. It translates serverless events into ASGI requests, letting you deploy existing async web apps without a rewrite.

FastAPI Container Build and Deploy Pipeline
Treat the Docker image as the immutable artifact: one build runs everywhere. Deploy FastAPI workers behind a load balancer, one process per container. The footgun is baking secrets into the image or running multiple processes; that breaks horizontal scaling.
FastAPI: Validating Models with Pydantic's Field
Pydantic's Field adds guardrails directly to your data model's attributes. Use it to enforce constraints like string length (max_length=50) or numeric ranges (gt=0), making your models self-validating.

Pydantic: Reusable Validation with Annotated Types
Pydantic's Annotated attaches validation logic directly to a type, making it reusable. Define a custom type like SquareNumber once and apply it to any model field, ensuring consistent validation without repeating code.
FastAPI's StreamingResponse: Send Data in Chunks
StreamingResponse sends data piece by piece, like a live broadcast, instead of sending a complete file all at once. This keeps your server's memory low for huge responses like file downloads, video streams, or live data from AI models.

Layered Architecture: Separating API from Business Logic
A layered architecture separates your API into distinct jobs: routing, controlling, and serving. This keeps code maintainable, like an organized toolbox. It's crucial for growing FastAPI apps.

asyncio Streams: High-Level Async Network I/O
asyncio Streams are like async file handles for the network. You get a reader/writer pair to await data, simplifying TCP clients and servers for basic protocols. The footgun: the default buffer limit is small; reading large data will fail unexpectedly.
ARQ for FastAPI: Async Background Tasks
ARQ lets your FastAPI app offload heavy work to background workers, keeping the API responsive. It's a task queue built for asyncio. Use it for slow tasks like sending emails or processing data. The footgun is using blocking task libraries with async code.
Serialize Pydantic Models with model_dump
model_dump turns a Pydantic model into a plain Python dict, bridging typed objects and JSON serializers in FastAPI endpoints. Call it when you need raw data before returning a response. Do not confuse it with model_dump_json, which emits a string, not a dict.
Per-Field Validation with @field_validator
@field_validator scrubs a single Pydantic field before it enters the model. Use it for rules like 'password must contain a digit' or 'port must exceed 1024'. It only sees one field at a time, so cross-field checks belong in a model validator instead.