Advanced everything in Python & FastAPI, page 3

Python Async Context Managers
Async context managers let you await during setup and teardown. Use async with for database connections or streams where acquiring and releasing both need I/O. The footgun is applying @contextmanager to async cleanup, which cannot await and will crash.

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'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.

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.

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.

Testing WebSockets in FastAPI
Test a WebSocket conversation by scripting both sides. FastAPI's TestClient provides a websocket_connect context manager to send messages and assert responses sequentially, which is crucial for testing chats or live data feeds.
Mocking with Pytest's monkeypatch
Pytest's monkeypatch is a temporary stunt double for your code, safely swapping out functions or environment variables for a single test. Use it to isolate tests from network calls or filesystem access.

Celery: Offloading Work from Your FastAPI App
Celery lets your web app offload slow tasks to a separate process, keeping your API responsive. Use it for tasks that can't finish in a single HTTP request, like sending bulk emails or processing images.
CSRF: Double Submit Cookies for Stateless Backends
Double Submit Cookies stop CSRF by requiring a secret in two places: a cookie and a request header. The server just checks if they match. It's useful for stateless APIs where storing server-side tokens is impractical.
OpenID Connect (OIDC): Authentication as a Service
OIDC lets you delegate user login to a trusted third party, like "Sign in with Google." Your app gets a verifiable token saying who the user is, without handling their password. It's used for SSO in web apps.
SQLAlchemy: Control When Your Relationships Load
SQLAlchemy's default lazy loading is convenient but can cause an N+1 query storm. Use eager loading (joinedload, selectinload) for collections you'll access to prevent many database round trips.

Debugging Python's Asyncio
Debugging asyncio is about finding what's blocking the single-threaded event loop. Use its debug mode to detect slow callbacks and run_in_executor to offload CPU-bound work. The biggest mistake is calling blocking code directly, which stalls the entire app.

asyncio Event Loop Policies: A Deprecated Pattern
Think of an event loop policy as the global factory for asyncio's event loops, controlling which loop is created and how it's retrieved. It was used to swap implementations, but the entire API is deprecated in Python 3.14 and will be removed in 3.16.

asyncio: Transports Move Bytes, Protocols Decide Which Bytes
asyncio Transports are the "how" (moving bytes), while Protocols are the "what" (deciding which bytes to send). They're the low-level foundation for libraries handling raw socket I/O.

Async Generators: `yield` in an `async` World
Async generators let you write I/O-bound data streams with the elegance of yield. An async def function with yield produces values one at a time, pausing for I/O without blocking. This is ideal for streaming data from a database.

FastAPI: Mounting Independent Sub-Applications
Mounting delegates a URL prefix to a separate FastAPI app, giving it its own isolated logic and API docs. Use it to combine microservices or isolate domains. The footgun: the main app's dependencies and middleware do not apply to the sub-app.
Accessing the Raw Request Object in FastAPI
Think of it as dropping to a lower level. Instead of FastAPI handing you validated data, you grab the raw Starlette HTTP request yourself. Use this for data not covered by standard declarations, like a client's IP.
Overriding FastAPI Dependencies for Testing
Overriding dependencies lets you swap real components for fakes during tests. This is vital for isolating tests from external services like auth providers or databases, letting you control inputs and avoid slow, flaky network calls.
FastAPI's Security Utility: Dependencies for Auth
FastAPI's Security utility is a specialized Depends for authentication. It signals to OpenAPI that a dependency is required for security, enabling interactive docs. Use it to protect endpoints by injecting the authenticated user.
FastAPI: Setting Custom Response Headers
Set custom HTTP headers in FastAPI by adding a Response parameter to your endpoint. This lets you add metadata like trace IDs without changing your return data. The footgun is thinking you must return the Response object; just return your data as usual.
We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.
See open roles