How do you apply a dependency to an APIRouter without per-endpoint signatures?
FastAPI router-level DI.
pass Depends() to APIRouter dependencies parameter; runs before every route in that router and shows in docs.
using middleware or manual decorators over the native dependencies argument.
WHAT THIS TESTS: This question checks whether you know that FastAPI's APIRouter class provides a first-class dependencies parameter for shared injection across a group of routes, rather than forcing repetition in every path operation signature. At a senior level, it also surfaces whether you understand the boundary between router-level and endpoint-level concerns, and why native framework hooks are preferable to custom wrapping.
A GOOD ANSWER COVERS: First, state that APIRouter accepts a dependencies argument in its constructor. Second, explain that you populate it with Depends instances so the framework handles injection automatically for every route mounted under that router. Third, note that this keeps individual endpoint functions clean and focused on their specific inputs and outputs. Fourth, mention that router-level dependencies compose with endpoint-level dependencies rather than replacing them, so you can still add per-path overrides or additional checks where needed.
COMMON WRONG ANSWERS: Recommending middleware to enforce authentication or shared logic on a subset of endpoints; middleware runs on every request and is not router-aware without path hacking. Suggesting a custom decorator that wraps path operation functions; this breaks FastAPI's automatic OpenAPI schema generation and dependency resolution. Manually adding the same dependency argument to every endpoint signature; this violates DRY and makes refactors painful.
LIKELY FOLLOW-UPS: How do router dependencies interact with endpoint dependencies when both are present? What happens to dependency caching and yield dependencies when they are declared at the router level? How would you override a router dependency in your test suite using dependency_overrides_provider? Can you combine router tags and router dependencies to enforce both documentation grouping and shared behavior?
ONE CONCRETE EXAMPLE: Imagine a user router that requires authentication on every endpoint. Instead of adding current_user: User = Depends(get_current_user) to ten separate path operations, you create the router with router = APIRouter(prefix="/users", dependencies=[Depends(get_current_user)]). Every GET, POST, or DELETE under that router now enforces authentication automatically, while each endpoint signature remains minimal. If one endpoint needs an extra admin check, you add a second dependency directly to that path operation and FastAPI resolves both.
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.