Performance: Shared dependencies
This affects server response time and resource usage by reusing common logic or resources across multiple routes.
Jump into concepts and practice - no test required
from fastapi import Depends from fastapi import FastAPI app = FastAPI() shared_db = None def get_shared_db(): global shared_db if shared_db is None: shared_db = create_new_db_connection() try: yield shared_db finally: pass # Do not close shared connection here @app.get('/items') async def read_items(db=Depends(get_shared_db)): return db.query_items() @app.get('/users') async def read_users(db=Depends(get_shared_db)): return db.query_users()
from fastapi import Depends from fastapi import FastAPI app = FastAPI() def get_db(): db = create_new_db_connection() try: yield db finally: db.close() @app.get('/items') async def read_items(db=Depends(get_db)): return db.query_items() @app.get('/users') async def read_users(db=Depends(get_db)): return db.query_users()
| Pattern | Resource Usage | Request Latency | Throughput | Verdict |
|---|---|---|---|---|
| Separate dependency per endpoint | High (multiple connections) | Higher (connection setup per request) | Lower | [X] Bad |
| Shared dependency instance | Low (single shared connection) | Lower (reuse connection) | Higher | [OK] Good |
Depends() in FastAPI for shared dependencies?Depends()Depends() is used in FastAPI to declare dependencies that can be shared across multiple routes.
Using shared dependencies helps reuse code and keep the app clean and maintainable.
Depends(function_name) inside the function parameters.db=Depends(get_db). def get_db(): return Session(); @app.get('/items') def read_items(db=get_db()): pass calls the function directly, which is incorrect. def get_db(): return Session(); @app.get('/items') def read_items(db: Session): pass lacks Depends, so no injection happens. def get_db(): return Session(); @app.get('/items') def read_items(db=Depends()): pass uses Depends without a function, which is invalid./items/42?
from fastapi import FastAPI, Depends
app = FastAPI()
def common_dep():
return "shared value"
@app.get('/items/{item_id}')
def read_item(item_id: int, value: str = Depends(common_dep)):
return {"item_id": item_id, "value": value}common_dep returns the string "shared value". FastAPI injects this into the value parameter via Depends(common_dep).item_id from the path and value from the dependency. So the output will be {"item_id": 42, "value": "shared value"}.from fastapi import FastAPI, Depends
app = FastAPI()
def get_token():
return "token123"
@app.get('/secure')
def secure_route(token: str = Depends()):
return {"token": token}token uses Depends() without specifying the dependency function. This is incorrect syntax.Depends(get_token).yield inside the dependency function. This allows setup before yield and cleanup after.yield that creates the session, yields it, then closes it after -> Option B