Skip to content

include_router: How can I get the return of a dependency callable at the decorator level #424

@jonDel

Description

@jonDel

Description

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions