Complete the code to declare a global dependency in FastAPI.
from fastapi import FastAPI, Depends app = FastAPI(dependencies=[Depends([1])]) def common_dependency(): return "common value"
The global dependency is passed as Depends(common_dependency) in the dependencies list when creating the FastAPI app.
Complete the code to add a global dependency that returns a header value.
from fastapi import FastAPI, Depends, Header, HTTPException app = FastAPI(dependencies=[Depends([1])]) def get_token_header(x_token: str = Header(...)): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="Invalid X-Token") return x_token
The global dependency is the function get_token_header which checks the header token.
Fix the error in the global dependency declaration.
from fastapi import FastAPI, Depends app = FastAPI(dependencies=[1]) def verify_user(): pass
The dependencies parameter expects a list of dependencies, so it must be wrapped in square brackets.
Fill both blanks to create a global dependency that logs each request.
from fastapi import FastAPI, Depends import logging logging.basicConfig(level=logging.INFO) def log_request(): logging.info("Request received") app = FastAPI(dependencies=[Depends([1])]) @app.get("/items/") def read_items(log=Depends([2])): return {"message": "Items list"}
The global dependency and the endpoint dependency both use the log_request function to log requests.
Fill all three blanks to create a global dependency that checks a token and a user role.
from fastapi import FastAPI, Depends, Header, HTTPException app = FastAPI(dependencies=[Depends([1])]) def verify_token(x_token: str = Header(...)): if x_token != "secret-token": raise HTTPException(status_code=400, detail="Invalid token") return x_token def verify_role(token: str = Depends(verify_token)): if token != "secret-token": raise HTTPException(status_code=403, detail="Not authorized") return True @app.get("/secure-data") def secure_data(role=Depends([2])): return {"access": "granted"} app.dependencies = [Depends([3])]
The global dependency uses verify_token first. The endpoint depends on verify_role, which itself depends on verify_token. The last app declaration uses verify_role as a global dependency.