Search code examples
pythondependency-injectionfastapi

Passing in arguments to Dependency function makes it recognized as a Query Parameter


Take a look at the following Route Handler

@some_router.post("/some-route") 
async def handleRoute(something = Depends(lambda request : do_something(request, "some-argument"))):     
    return JSONResponse(content = {"msg": "Route"}, status_code = 200)

So the dependency function do_something takes in a request and a string value. But, passing it in like so makes it so that it is recognized as a query parameter now even though it shouldn't. It is just an argument that is needed for the dependency function.

enter image description here

The do_something implementation

async def do_something(request: Request, value: str):
pass

This is obviously an example code. How can I pass in the request along with the string value into the do_something dependency function without making it recognized as a query parameter?

  • Rewrote Route Handler

  • Used default arguments but that's not how FastAPI's dependency injections works so no good

  • Maybe the use of lambda itself forces FastAPI to recognize it as a Query Parameter?

  • Tried setting a type for "request" as "Request" but then I get a syntax issue, tried wrapping it in parentheses and it still didn't work.


Solution

  • My current solution to this is the following:

    def get_do_something(value: str):
        async def fixed_do_something(request: Request):
            return await do_something(request, roles)
        return fixed_do_something
    

    Notice how instead of directly passing the request with your additional parameters, you are now using a wrapper function. This wrapper function handles the additional parameters and passes them to the nested function. Following this convention simplifies development and makes the process more efficient.

    @some_router.post("/some-route") 
    async def handleRoute(something = Depends(get_do_something('some-value'))):     
        return JSONResponse(content = {"msg": "Route"}, status_code = 200)