More in Python & FastAPI — page 9
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.
Testing Async FastAPI with pytest-asyncio
To test async code, your tests must also be async. `pytest-asyncio` lets you write `async def test_...` functions to `await` operations like database checks after an API call.
Run One Test with Many Inputs using pytest.parametrize
Run one test function with many inputs using `@pytest.mark.parametrize`, avoiding repetitive code. It's ideal for checking a function against various inputs, edge cases, and expected failures. The footgun: mutable parameters like lists are passed by reference.
pytest Fixtures: Reusable Test Setups
Pytest fixtures are reusable functions for test setup, like creating sample data. Your tests request them by name as arguments, and pytest automatically runs them and injects the results.
FastAPI's TestClient: Test Your API Without a Live Server
FastAPI's TestClient simulates API requests in-memory, letting you test endpoints without a live server. Use it with pytest to verify status codes and responses. The main footgun is forgetting to `pip install httpx`, as it's a required dependency.

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.
Custom FastAPI Middleware: The BaseHTTPMiddleware Helper
FastAPI's BaseHTTPMiddleware lets you wrap endpoints to run code before and after they execute. Use it to add custom headers or log request times. The footgun: reading `request.body()` in the middleware will break the endpoint, as the body can only be read…
FastAPI Background Tasks: Don't Make the Client Wait
FastAPI background tasks let you run slow operations, like sending an email, *after* returning a response. This keeps your API fast. The main footgun: these are fire-and-forget; a server crash means the task is lost without a real message queue.
CORSMiddleware: Unblocking Your Frontend from Your Backend
CORS is a browser security rule, not a server bug. Use FastAPI's CORSMiddleware to tell browsers which frontends (e.g., `localhost:3000`) are allowed to fetch data from your API (e.g., `localhost:8000`).
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.
Refresh Tokens: Persistent Sessions Without Re-Authentication
A refresh token is a long-lived credential used to get a new, short-lived access token without re-authenticating. It's how apps keep you logged in for weeks. The footgun is storing it insecurely, letting attackers mint access tokens forever.

FastAPI RBAC: Using OAuth2 Scopes for Permissions
Treat OAuth2 scopes as a list of permissions. Instead of checking a user's role, you check if their token has the required scope (e.g., `items:write`) for an endpoint. FastAPI's Security dependency automates this check.

FastAPI: Fine-Grained Permissions with OAuth2 Scopes
Think of OAuth2 scopes as permissions on a keycard. A token gets you in the building, but scopes like `items:read` or `items:write` define which rooms you can enter. Use them in FastAPI to grant granular access.
API Keys: Simple Server-to-Server Authentication
An API key is a simple secret token a client sends to prove its identity, often in a request header. It's ideal for machine-to-machine communication where a user login flow is unnecessary. Footgun: Never send keys in URL query parameters.

HTTP Basic Auth: Simple but Insecure Access Control
HTTP Basic Auth is a simple gatekeeper for your API, prompting users for a username and password directly in the browser. It's useful for internal tools, but never use it over unencrypted HTTP as credentials are sent in a trivially decodable format.

OAuth2 Password Flow: Trading Credentials for a Token
The OAuth2 Password Flow trades a user's credentials for a temporary access token. It's used in trusted first-party apps, like a mobile app logging into its own backend, to avoid sending a password with every API call.

Password Hashing with Python's Passlib
Passlib turns plaintext passwords into secure, salted hashes that are safe to store. Use it in any Python app with user accounts to handle logins. The footgun: never compare hashes directly; always use the `.verify()` method to prevent timing attacks.
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.
Beanie: Python Objects as MongoDB Documents
Beanie maps Pydantic models to MongoDB documents, letting you interact with the database using Python objects instead of raw queries. Use it in async apps like FastAPI for rapid, type-safe CRUD.