Performance: Depends function basics
This affects server response time and resource usage during request handling.
Jump into concepts and practice - no test required
from fastapi import Depends @app.get('/items') def read_items(user = Depends(get_user)): # use user return items def get_user(): # fetch user from database return user
def get_user(): # fetch user from database return user @app.get('/items') def read_items(): user = get_user() # use user return items
| Pattern | Dependency Calls | Redundancy | Response Time Impact | Verdict |
|---|---|---|---|---|
| Manual calls inside endpoint | Multiple per request | High | Increases response time | [X] Bad |
| Using Depends parameter | Single per request | Low | Optimized response time | [OK] Good |
Depends function in FastAPI?Depends is used to declare dependencies that FastAPI will automatically provide to your route functions.Depends?db=Depends(get_db), which is the proper way to declare a dependency./items/ endpoint?from fastapi import FastAPI, Depends
app = FastAPI()
def get_number():
return 42
@app.get('/items/')
def read_items(number: int = Depends(get_number)):
return {"number": number}get_number function returns 42, and FastAPI injects this value into the number parameter.Depends? How to fix it?from fastapi import FastAPI, Depends
app = FastAPI()
def get_user():
return "Alice"
@app.get('/user/')
def read_user(user: str = Depends):
return {"user": user}Depends without specifying the dependency function, which is incorrect.Depends(get_user) to tell FastAPI which function to call for the dependency.Depends to share a database session across multiple routes without repeating code? Choose the best approach.