Performance: Dependencies with parameters
This affects server response time and resource usage during request handling.
Jump into concepts and practice - no test required
from fastapi import Depends, FastAPI app = FastAPI() def get_db_connection(param: str): # Simulate expensive setup return f"DB connection with {param}" def get_param(): return "my_param" @app.get("/items/") async def read_items(db=Depends(lambda: get_db_connection(get_param()))): return {"db": db}
from fastapi import Depends, FastAPI app = FastAPI() def get_db_connection(param: str): # Simulate expensive setup return f"DB connection with {param}" @app.get("/items/") async def read_items(db=Depends(get_db_connection)): return {"db": db}
| Pattern | Dependency Calls | Parameter Passing | Response Time Impact | Verdict |
|---|---|---|---|---|
| Implicit parameter dependency | Multiple per request | No explicit passing | High due to repeated calls | [X] Bad |
| Explicit parameter passing with caching | Single or cached call | Explicit and controlled | Low, efficient reuse | [OK] Good |
from fastapi import FastAPI, Depends
app = FastAPI()
def get_multiplier(factor: int):
def multiplier(value: int):
return value * factor
return multiplier
@app.get("/multiply")
async def multiply(value: int, multiply_func = Depends(get_multiplier(3))):
return {"result": multiply_func(value)}def get_limit(limit: int = 10):
return limit
@app.get("/items")
async def read_items(limit = Depends(get_limit(limit=20))):
return {"limit": limit}def common_dep(param: str):
def dependency():
return f"Value is {param}"
return dependency
@app.get("/route1")
async def route1(dep = Depends(common_dep("A"))):
return {"msg": dep}
@app.get("/route2")
async def route2(dep = Depends(common_dep("B"))):
return {"msg": dep}