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
@firstname.lastname@example.org 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
async def get_third_party_result(client=Depends(get_client)): ... await client.get(url)
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)
And run it as,
import asyncio asyncio.run(hello())
Now I get proper result for further testing.
Thanks for your reading.