Search code examples
dependency-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 string value. But passing it in like so makes it so that its recognized as a query parameter now even though it shouldn't. Its just an argument thats 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 be 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.

  • Asked ChatGPT for guidance


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're now using a nested function. This nested function handles the additional requirements. 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)