Complete the code to declare a simple dependency function in FastAPI.
from fastapi import Depends, FastAPI app = FastAPI() def common_parameters(): return {"q": "fastapi"} @app.get("/items/") async def read_items(params: dict = Depends([1])): return params
The dependency function common_parameters is passed to Depends() to inject its return value.
Complete the code to declare a sub-dependency function that depends on another dependency.
from fastapi import Depends, FastAPI app = FastAPI() def common_parameters(): return {"q": "fastapi"} def query_extractor(params: dict = Depends([1])): return params.get("q") @app.get("/search/") async def search(q: str = Depends(query_extractor)): return {"query": q}
The sub-dependency query_extractor depends on common_parameters to get the parameters dictionary.
Fix the error in the sub-dependency declaration by completing the blank.
from fastapi import Depends, FastAPI app = FastAPI() def common_parameters(): return {"q": "fastapi"} def query_extractor(params: dict = Depends([1])): return params.get("q") @app.get("/items/") async def read_items(q: str = Depends(query_extractor)): return {"query": q}
The sub-dependency query_extractor must depend on common_parameters to receive the parameters dictionary.
Fill both blanks to create a sub-dependency that extracts a header and then use it in the endpoint.
from fastapi import Depends, FastAPI, Header app = FastAPI() def user_agent_header(user_agent: str = [1]): return user_agent @app.get("/headers/") async def read_headers(user_agent: str = Depends([2])): return {"User-Agent": user_agent}
The sub-dependency user_agent_header uses Header("User-Agent") to extract the header value. The endpoint depends on user_agent_header.
Fill all three blanks to create nested dependencies where the endpoint depends on a sub-dependency that depends on another dependency.
from fastapi import Depends, FastAPI app = FastAPI() def common_parameters(): return {"token": "abc123"} def verify_token(params: dict = Depends([1])): token = params.get([2]) if token != "abc123": raise Exception("Invalid token") return token @app.get("/secure-data/") async def secure_data(token: str = Depends([3])): return {"token": token}
The sub-dependency verify_token depends on common_parameters to get the parameters dictionary. It extracts the token key. The endpoint depends on verify_token.