DEV Community

Ahsanuzzaman Khan
Ahsanuzzaman Khan

Posted on

AttributeError: 'Depends' object has no attribute 'get' FastAPI

While working with FastAPI I've faced a problem about the above mention error. Though it is quite common but I didn't face it before.

My use case is, I put a dependency injection which works perfectly fine within endpoint functions (the ones with @app.post/@app.get decorators), but somehow doesn't work within plain functions.

My code block has given below,

async def get_client():
    async with AsyncClient() as client:
        yield client
Enter fullscreen mode Exit fullscreen mode
async def get_third_party_result(client=Depends(get_client)):
    ...
    await client.get(url)
Enter fullscreen mode Exit fullscreen mode

In summary what have I found denoted below. The actual link is here.

you can't use Depends in your own functions, it has to be in FastAPI functions, mainly routes. You can, however, use Depends in your own functions when that function is also a dependency, so could can have a chain of functions.
Eg, a route uses Depends to resolve a 'getcurrentuser', which also uses Depends to resolve 'getdb', and the whole chain will be resolved. But if you then call 'getcurrentuser' without using Depends, it won't be able to resolve 'getdb'.
What I do is get the DB session from the route and then pass it down through every layer and function. I believe this is also better design.

For my purpose, anyway I need to test it explicitly. Thus to get rid of it, I prepare another method to get the result of actual function.

async def hello():
   async with httpx.AsyncClient() as client:
     return await get_third_party_result(client=client)
Enter fullscreen mode Exit fullscreen mode

And run it as,

import asyncio

asyncio.run(hello())
Enter fullscreen mode Exit fullscreen mode

Now I get proper result for further testing.
Thanks for your reading.

Top comments (2)

Collapse
 
bofcarbon1 profile image
Brian Quinn • Edited

Yes. This was frustrating me. Inserting a document into MongoDB from FastAPI. I had a direct request to repo with a odmantic datbase connection and a depends that was working. When I added a service layer got this error. I think was missing my layered call from a request-service-repo. I pull data from another web site using Beautiful Soup. Once I completed the chain of database configuration engine with dependency it worked. I like FastAPI.

Collapse
 
eswari profile image
Eswari Jayakumar

Thanks for the article ! It is helpful !