question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] include_router: How can I get the return of a dependency callable at the decorator level

See original GitHub issue

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?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:16
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

62reactions
tiangolocommented, Feb 10, 2020

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.

10reactions
prabhatsharmacommented, Mar 19, 2021

I think we should add this to documentation at https://fastapi.tiangolo.com/tutorial/bigger-applications/

Read more comments on GitHub >

github_iconTop Results From Across the Web

Dependencies in path operation decorators - FastAPI
Dependencies in path operation decorators¶. In some cases you don't really need the return value of a dependency inside your path operation function....
Read more >
tiangolo/fastapi - Gitter
AssertionError: A parameter-less dependency must have a callable ... you can write dependency to specifically check levels or return it and in your...
Read more >
Fastapi How to access attributes of class based dependency ...
I've had a similar question in the past. See. FastAPI get user ID from API key. Basically, save the dependency response/values in the ......
Read more >
FastAPI top-level dependencies - Sebastián Ramírez - Medium
include_router () when you want to override some defaults that can't (or shouldn't) be set in APIRouter directly. Set them in FastAPI() only...
Read more >
The Ultimate FastAPI Tutorial Part 11 - Dependency Injection ...
Define a callable (usually a function, but it can also be a class in rarer cases) which returns or yields*** the instantiated object...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found