Instructions for FastAPI Dependencies
Manage dependencies in FastAPI:
- •
Defining Dependencies:
- •Functions:
def common_parameters(q: str = None): return {"q": q}. - •Classes: With
__call__method.
- •Functions:
- •
Injection:
- •In paths:
@app.get("/items/", dependencies=[Depends(common_parameters)]). - •In params:
def get_items(commons: dict = Depends(common_parameters)): ....
- •In paths:
- •
Sub-Dependencies:
- •Nest:
def sub_dep(): ...thendef main_dep(sub=Depends(sub_dep)): ....
- •Nest:
- •
Caching:
- •Automatic per request.
- •Override with
cached=Falsein Depends.
- •
Scopes:
- •Application, router, or path level.
- •Use for DB sessions: Yield for cleanup.
- •
Best Practices:
- •Use for authentication, logging, rate limiting.
- •Async dependencies for async code.
- •Test dependencies separately.
References
Use the shared references located at: ../_shared/reference.md