Consider a FastAPI app with two routers sharing a dependency that returns a user ID. What will the response be when calling /items/?
from fastapi import FastAPI, Depends, APIRouter app = FastAPI() async def get_user_id(): return "user123" router1 = APIRouter(dependencies=[Depends(get_user_id)]) @router1.get("/items/") async def read_items(): return {"message": "Items accessed"} router2 = APIRouter(dependencies=[Depends(get_user_id)]) @router2.get("/users/") async def read_users(): return {"message": "Users accessed"} app.include_router(router1) app.include_router(router2)
Think about which router handles the /items/ path and what the shared dependency returns.
The /items/ endpoint is defined in router1, which includes the shared dependency get_user_id. The endpoint returns a fixed message, so the output is {"message": "Items accessed"}.
Given two routers, which code snippet correctly applies the same dependency to both routers?
from fastapi import APIRouter, Depends async def common_dep(): return "common" router1 = APIRouter() router2 = APIRouter() # Which option correctly adds common_dep as a shared dependency?
Check how dependencies are passed as a list to the APIRouter constructor.
Dependencies must be passed as a list of Depends instances to the dependencies parameter of APIRouter. Option A correctly does this for both routers.
Examine the code below. When running the app, a runtime error occurs related to the shared dependency. What causes this error?
from fastapi import FastAPI, Depends, APIRouter app = FastAPI() async def get_db(): raise RuntimeError("DB connection failed") router = APIRouter(dependencies=[Depends(get_db)]) @router.get("/data") async def read_data(): return {"data": "sample"} app.include_router(router)
Look at what the dependency function does when called.
The dependency get_db raises a RuntimeError intentionally. This causes any endpoint depending on it to fail at runtime.
Given this FastAPI router with a shared dependency that returns a string, what is the value of user inside the endpoint?
from fastapi import APIRouter, Depends async def get_current_user(): return "alice" router = APIRouter(dependencies=[Depends(get_current_user)]) @router.get("/profile") async def profile(user: str = Depends(get_current_user)): return {"user": user}
Consider how FastAPI resolves dependencies when declared both in router and endpoint.
FastAPI calls the dependency once and injects the returned value. The user parameter receives the string "alice".
Which is the main advantage of applying dependencies at the router level instead of individually on each endpoint?
Think about code reuse and how dependencies apply to multiple endpoints.
Applying dependencies at the router level avoids repeating the same dependency on every endpoint. It runs the dependency once per request for all endpoints in that router.