As @Omer Alkin correctly noted, a dependency needs to be specified in the path operation parameter list when we want to use its return value (user or token or smth.). Here's an example from the documentation:
async def get_current_user(token: str = Depends(oauth2_scheme)):
user = fake_decode_token(token)
return user
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
If the return value of dependency is not important to us or it is not returned, but only a side effect is important, for example, the dependency throws an exception, then we can specify the dependency in the path operation decorator.
In this case, we can also execute the dependency (do authentication) immediately for a group of operations, using APIRouter:
async def get_token_header(x_token: str = Header(...)):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
router = APIRouter(
prefix="/items",
tags=["items"],
dependencies=[Depends(get_token_header)],
responses={404: {"description": "Not found"}},
)
It should also be noted that you can reuse the same dependency in the path operation or its sub dependencies, as FastAPI implements the cache policy by default:
If one of your dependencies is declared multiple times for the same path operation, for example, multiple dependencies have a common sub-dependency, FastAPI will know to call that sub-dependency only once per request.