tezvyn:

FastAPI Global Dependencies: DRY Your API Logic

AI-drafted, machine-checkedSource: fastapi.tiangolo.comintermediate

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.

WHY IT EXISTS Global dependencies solve the problem of repeating the same logic for every endpoint. Manually adding an authentication dependency to dozens of path operations is tedious and error-prone. A global dependency lets you define this logic once and have it apply everywhere, following the Don't Repeat Yourself (DRY) principle.

THE MENTAL MODEL Think of a global dependency as a universal middleware, but with the full power of FastAPI's dependency injection system. It's a mandatory entry requirement for every endpoint in your application, like requiring a valid ticket to enter any part of a theme park, not just specific rides. If the check fails, the request is stopped before it even reaches the endpoint's logic.

HOW IT WORKS You pass a list of dependencies to the FastAPI application instance itself using the dependencies argument. For example: app = FastAPI(dependencies=[Depends(verify_api_key)]). For every incoming request to any path operation, FastAPI will first resolve and execute these global dependencies. If any global dependency raises an exception, the request is halted immediately with an error response.

WHEN TO USE IT Use it for truly global, application-wide logic. Three common cases: first, mandatory authentication or API key checks that apply to the entire service; second, setting global context variables like a request ID for logging; third, universal request logging or metrics collection that needs to run for every single call.

WHEN NOT TO USE IT Avoid using global dependencies for logic that isn't universal. If a dependency is only needed for a group of related endpoints (e.g., everything under /admin), apply it to an APIRouter instead. If it's for a single endpoint, apply it directly to the path operation decorator. Misusing global dependencies for specific logic makes the code less clear and harder to maintain.

ONE CANONICAL EXAMPLE To require two specific headers, X-Token and X-Key, on every single request, you can define two dependency functions, verify_token and verify_key. Each function checks for its respective header and raises an HTTPException if it's missing or invalid. You then apply them globally: app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)]). Now, no request can be processed by any endpoint unless both valid headers are present.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.