Fastapi: [QUESTION] - Use request object in a dependency

Created on 25 Jun 2020  路  3Comments  路  Source: tiangolo/fastapi

First check

  • [X] I added a very descriptive title to this issue.
  • [X] I used the GitHub search to find a similar issue and didn't find it.
  • [X] I searched the FastAPI documentation, with the integrated search.
  • [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
  • [X] I already read and followed all the tutorial in the docs and didn't find an answer.
  • [X] I already checked if it is not related to FastAPI but to Pydantic.
  • [X] I already checked if it is not related to FastAPI but to Swagger UI.
  • [X] I already checked if it is not related to FastAPI but to ReDoc.
  • [X] After submitting this, I commit to one of:

    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.

    • I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.

    • Implement a Pull Request for a confirmed bug.

Example

I want to be able to do something like this:

from fastapi import FastAPI, Request

app = FastAPI()

def on_permissions(request: Request = Depends()):
    pass

@app.get("/{user_id}", dependencies=[Depends(OnReadUser)]
def read_user(user_id: int):
    return crud_user.get(id=user_id)

Description

I need to use the request in a dependency function. The goal is to create a permission/access control list and use it to authorize the user to use an endpoint based on the request fields and the permissions.

Additional context

If that's not possible, is there a way to get the endpoint path like what is described here: https://github.com/tiangolo/fastapi/issues/486 , but before sending it to the endpoint itself?

question

Most helpful comment

@HarrySky You don't need to use Depends() on Request, just use like:

def on_permissions(request: Request):
    pass

Because you're already passing the request from the endpoint :)

All 3 comments

@Kludex Did you find a solution? Would want to use Request in dependency function too

@HarrySky You don't need to use Depends() on Request, just use like:

def on_permissions(request: Request):
    pass

Because you're already passing the request from the endpoint :)

Thanks for reporting back and closing the issue :+1: :cake:

Was this page helpful?
0 / 5 - 0 ratings