More in Python & FastAPI — page 11
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 Global Dependencies: DRY Your API Logic
A FastAPI global dependency is like a bouncer for your entire API, running a check on every request. Use it for universal concerns like API key validation. The footgun is applying logic that should only affect a subset of routes, making your API rigid.
FastAPI's Dependency Caching: One Request, One Call
FastAPI dependencies are singletons for the life of a request. If multiple parts of your code ask for the same dependency (e.g., a database session), FastAPI runs it once, caches the result, and shares it. The footgun: this cache is per-request, not global.

FastAPI: Using Classes as Dependencies
Bundle related request parameters into a class instead of repeating them in every endpoint. FastAPI automatically creates an instance for you, cleaning up your code. This is ideal for shared logic like pagination. The footgun: FastAPI injects into `__init__`.

FastAPI's Depends: Let the Framework Handle Setup
Think of `Depends` as a pre-flight checklist for your API endpoints. You list required setup tasks, like getting a user or a database session, and FastAPI runs them for you. This is key for sharing logic like auth or database connections across many routes.
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.
FastAPI `yield` Dependencies for Setup and Teardown
A `yield` dependency is a context manager for your endpoints. Code before `yield` runs setup, like getting a DB connection; code after `yield` runs teardown.
FastAPI: Set Cookies Without Returning a Response Object
Inject a `Response` object into your endpoint to set cookies without manually building the whole response. Use this for session tokens while still returning data like a dict.
FastAPI: Use UploadFile for Efficient File Uploads
FastAPI handles file uploads as 'form data', giving you a streamable `UploadFile` object instead of a raw byte blob. Use this for endpoints like image or document submissions. The footgun is reading large files into memory instead of streaming them.

FastAPI: Returning HTML with HTMLResponse
Override FastAPI's default JSON output by using `HTMLResponse` to return a raw HTML string directly from an endpoint. It's for simple status pages or server-side rendered components.
FastAPI: Reading Request Cookies
FastAPI treats request cookies like any other parameter. Declare them directly in your endpoint's function signature using `Cookie()`, and the framework will extract the value for you. Use this for reading session IDs or user preferences.
Declaring Request Headers in FastAPI
Treat request headers like any other parameter in FastAPI. Declare them in your function signature to access values like `User-Agent` or `X-Token`. FastAPI automatically converts hyphens to underscores, so `User-Agent` is accessed via the `user_agent`…
FastAPI: Handling Form Data, Not Just JSON
FastAPI can handle classic HTML form data, not just JSON. Use `Form` to define expected fields in your endpoint, just like query parameters. It's ideal for login pages. The footgun: forgetting to `pip install python-multipart` will break form parsing.

Pydantic Computed Fields: Serialize Derived Values
A Pydantic computed field makes a derived value, like an area from width and length, part of your model's serialized output. Use it to include calculated attributes when calling `.model_dump()`.

Pydantic: Configuring Models with `model_config`
Think of `model_config` as the settings panel for your Pydantic models, letting you change validation rules like string length or immutability. Use it to enforce global constraints or make models immutable. The footgun is using the old `class Config:` from V1.

Pydantic's Data Coercion: From Raw Data to Python Types
Pydantic automatically converts raw data, like strings from a JSON request, into the Python types you declare. It's how FastAPI turns a JSON body into a typed Python object.

Nested Pydantic Models: Composing Complex Data
Use a Pydantic model as a field type inside another to build complex, nested structures. This is essential for modeling JSON with sub-objects, like a user with an address.

Pydantic: Required vs. Optional Fields
In Pydantic, a field is required by default. To make it optional, you must provide a default value, like `name: str = "guest"` or `age: int | None = None`. This is key for flexible API request bodies.
Starlette's Request Object: A Clean API for ASGI
Starlette's Request object is a high-level wrapper around the raw ASGI scope, providing a clean API for request data. Use it in endpoints to read headers, query params, or parse the body. The footgun: the request body can only be read once.
FastAPI: Use HTTPException to Return Client Errors
FastAPI's HTTPException is your tool for stopping an operation and sending a clean HTTP error. Raise it when business logic fails, like a missing database record. The footgun is catching it yourself; just `raise` it and let FastAPI do the rest.