I have the following scenario where I have a class representing a client to interact with an external service (such as Google Storage or another DB).
class SomeClient:
pass
Now, I have multiple endpoints that need to utilize this client. I'm wondering what would be considered a better approach in terms of reusability and performance: whether to create the client myself once and use it in each endpoint, or alternatively, use the dependency injection mechanism.
Creating it on my own:
from fastapi import APIRouter
router = APIRouter()
client = SomeClient()
@router.get("/")
def hello():
client.do_something()
return "hello"
Versus using dependency injection:
from fastapi import APIRouter, Depends
router = APIRouter()
@router.get("/")
def hello(client: SomeClient = Depends()):
client.do_something()
return "hello"
What are the pros and cons of each method? The first approach makes more sense for me in terms of performance (no need to create an object on each request) so I wonder if, and when, use the dependency injection mechanism.
Thanks.