[QUESTION] include_router: How can I get the return of a dependency callable at the decorator level
See original GitHub issueDescription
Is it possible to get the return of a dependency callable declared at the decorator level? Let me clarify why I need this with the following code, borrowed and modified from the bigger-aplications tutorial:
from fastapi import Depends, FastAPI, Header, HTTPException
from .routers import items, users
app = FastAPI()
async def get_token_header(x_token: str = Header(...)):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
return "Foobar"
app.include_router(
items.router,
prefix="/items",
tags=["items"],
dependencies=[Depends(get_token_header)],
responses={404: {"description": "Not found"}},
)
My application has a lot of endpoints, and every one, except for the “token”, has the same dependency, which is a jwt token obtained from the “token” endpoint, sent as a header to the other endpoints, that must be validated. So far, so good, except that I need, besides validating the token, getting the user information obtained from parsing that token. Following the code above, it would be something like, inside the items module, retrieving somehow that “Foobar” return from get_token_header. My “items” router(module) would look something like the code bellow.
from fastapi import APIRouter, HTTPException
router = APIRouter()
@router.get("/")
async def read_items():
do something with the get_token_header defined as a dependency in the include_router level
The only alternative I see would be defining the dependency callable elsewhere and import and use it in every router and every path and subpath operation, which I think is too much code repetition. Besides, can I access that “responses”, defined at the include_router level? Or it is just for documentation in OpenAPI format?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:16
- Comments:11 (4 by maintainers)
Top GitHub Comments
Thanks for the discussion here!
You can declare the same dependency at the router or decorator level and then declare it again in the path operation to get its value.
It won’t be evaluated twice, it doesn’t add any extra computation, there’s a dependency cache in place that stores the values of already solved dependencies for a given request (you can also disable the cache for a specific dependency, but that’s not what you need here).
So yeah, declare it at the top level to ensure everything in a router has the same security, and then at the path operation level again to get the solved value if you need it.
I think we should add this to documentation at https://fastapi.tiangolo.com/tutorial/bigger-applications/