Using dependencies at the path, router, and global level
As we said, dependencies are the recommended way to create building blocks in a FastAPI project, allowing you to reuse logic across endpoints while maintaining maximum code readability. Until now, we’ve applied them to a single endpoint, but couldn’t we expand this approach to a whole router? Or even a whole FastAPI application? Actually, we can!
The main motivation for this is to be able to apply some global request validation or perform side logic on several routes without the need to add a dependency on each endpoint. Typically, an authentication method or a rate limiter could be very good candidates for this use case.
To show you how it works, we’ll implement a simple dependency that we will use across all the following examples. You can see it in the following example:
chapter05_path_dependency_01.py
def secret_header(secret_header: str | None = Header(None)) -> None: ...