Consider this FastAPI app where a global dependency adds a header. What will the response headers contain when you call /items/42?
from fastapi import FastAPI, Depends, Header app = FastAPI() def common_header(x_token: str = Header(...)): return x_token @app.get("/items/{item_id}", dependencies=[Depends(common_header)]) async def read_item(item_id: int): return {"item_id": item_id}
Think about what happens if the required header is missing in the request.
The dependency common_header requires the header x-token. If the client does not send it, FastAPI returns a 422 error before calling the path operation.
Given this FastAPI app, what will be the value of token_value inside the endpoint?
from fastapi import FastAPI, Depends app = FastAPI() def get_token(): return "secret-token" @app.get("/users/me", dependencies=[Depends(get_token)]) async def read_user(token_value: str = Depends(get_token)): return {"token": token_value}
Consider how FastAPI resolves dependencies when the same function is used globally and locally.
FastAPI calls the dependency function for each injection. The global dependency does not affect the local parameter. So token_value is "secret-token".
Choose the correct way to add a global dependency that runs for every request.
Check FastAPI docs for how to add global dependencies at app creation.
FastAPI accepts a dependencies parameter in the constructor to add global dependencies. Other options are invalid syntax or methods.
Given this code, why is the global dependency verify_token not executed when calling /open?
from fastapi import FastAPI, Depends def verify_token(): print("Token verified") app = FastAPI(dependencies=[Depends(verify_token)]) @app.get("/open") async def open_endpoint(): return {"message": "Open to all"}
Think about where print output goes in FastAPI apps.
The global dependency runs for every request. The print statement outputs to the server console, not the HTTP response. So the client sees the JSON response only.
Suppose you add two global dependencies that both require a header x-token. How does FastAPI handle this situation?
Consider how FastAPI resolves dependencies and parameters from requests.
FastAPI calls each dependency separately but uses the same request data. The header x-token is read once and passed to both dependencies.