Shared dependencies let you reuse code for things like authentication or database access across different parts of your app. This keeps your code clean and easy to manage.
0
0
Shared dependencies across routers in FastAPI
Introduction
When multiple API routes need the same authentication check.
When several routers require access to the same database session.
When you want to apply common headers or parameters to many routes.
When you want to keep your code DRY (Don't Repeat Yourself) by sharing logic.
When organizing a large app with many routers that share setup steps.
Syntax
FastAPI
from fastapi import FastAPI, APIRouter, Depends # Define a dependency function def common_dependency(): return "Shared value" # Create routers router1 = APIRouter(dependencies=[Depends(common_dependency)]) router2 = APIRouter(dependencies=[Depends(common_dependency)]) # Use routers in app app = FastAPI() app.include_router(router1) app.include_router(router2)
Use dependencies=[Depends(your_dependency)] when creating an APIRouter to share dependencies.
Dependencies listed here run before any route in that router.
Examples
This router requires token verification for all its routes.
FastAPI
from fastapi import APIRouter, Depends def verify_token(): # Imagine token verification here return True router = APIRouter(dependencies=[Depends(verify_token)])
All routes in this router get a database session automatically.
FastAPI
from fastapi import APIRouter, Depends def get_db(): db = "db session" try: yield db finally: pass # close db router = APIRouter(dependencies=[Depends(get_db)])
Sample Program
This example shows two routers sharing the same dependency that could add a common header or perform a check. Both routers have routes that return simple messages.
FastAPI
from fastapi import FastAPI, APIRouter, Depends from fastapi.responses import JSONResponse # Dependency function async def common_header(): return {"X-Common-Header": "Value"} # Router 1 with shared dependency router1 = APIRouter(dependencies=[Depends(common_header)]) @router1.get("/items") async def read_items(): return {"message": "Items from router1"} # Router 2 with same shared dependency router2 = APIRouter(dependencies=[Depends(common_header)]) @router2.get("/users") async def read_users(): return {"message": "Users from router2"} # Create app and include routers app = FastAPI() app.include_router(router1, prefix="/r1") app.include_router(router2, prefix="/r2")
OutputSuccess
Important Notes
Shared dependencies run for every request to routes in that router.
You can also add dependencies globally to the FastAPI app for all routes.
Dependencies can return values or perform actions like authentication or logging.
Summary
Shared dependencies help reuse code across multiple routers.
They keep your app organized and avoid repeating code.
Use dependencies=[Depends(your_dependency)] when creating routers.