2

With FastAPI's APIRouter, I know you can pass a dependency through the dependencies parameter. Every example I see though has a dependency that doesn't return anything. I've been diving through the code, but I'm guessing I'm not understanding how to do what I want, and would be fine knowing that is not possible; I can always add the dependency to every route.

my_module = APIRouter(prefix="/abc", dependencies=[Depends(get_permissions)])

@my_module.get('/')
def route_1(permissions: Permissions):
    pass

@my_module.get('/a')
def route_2(permissions: Permissions):
    pass

I want to do something like this where the permissions are retrieved via get_permissions and injected into each route.

Chris
  • 18,724
  • 6
  • 46
  • 80
Rohit
  • 3,018
  • 2
  • 29
  • 58
  • You can't have a global dependency returning a value afaik, however, you can simply have it check for permissions and throw an error if the user has no permission (by the authorization header for example). If you want to get the permissions themselves, you need to put them in the route as `x: type = Depends(func)` – Ahmed I. Elsayed Oct 18 '22 at 00:36

1 Answers1

4

The way around this issue is to store the returned value to request.state, as described in this answer (see State implementation):

from fastapi import Request

def get_permissions(request: Request):
    request.state.my_attr = 'some value'
    # ...

Afterwards, inside the endpoints, you can retrieve that attribute, as described in this answer and as shown below:

router = APIRouter(prefix='/abc', dependencies=[Depends(get_permissions)])

@router.get('/')
def route_1(request: Request):
    return request.state.my_attr
Chris
  • 18,724
  • 6
  • 46
  • 80