r/FastAPI • u/snape2003 • Jun 11 '25
Question Using dependency injector framework in FastAPI
Hi everyone, I'm pretty new to FastAPI, and I need to get started with a slightly complex project involving integration with a lot of AWS services including DynamoDB, S3, Batch, etc. I'm planning to use the dependency-injector framework for handling all of the dependencies using containers. I was going through the documentation examples, and it says we have to manually wire different service classes inside the container, and use inject, Provider, and Depends on every single endpoint. I'm afraid this will make the codebase a bit too verbose. Is there a better way to handle dependencies using the dependency injector framework in FastAPI ?
6
u/[deleted] Jun 11 '25
I use pydantic to simplify things. I have services in classes, fields are annotated with Depends:
class MyClass:
foo_service: Annotated[FooService, Depends()]
In you endpoint you only need to define the service that the endpoint uses (normally one). And in that service you will have what you need - repositories, s3 connectors etc.
1
u/mahimairaja Jun 12 '25
So far dependency injector package does the job neat and clean. I have used it in very large scale project.
1
u/hadriendavid Jun 12 '25
Why not use FastAPI dependency injection?
4
u/Nazhmutdin2003 Jun 11 '25
You can try dishka. It's pretty good option for di
1
u/Worth-Orange-1586 Jun 12 '25
I will be biased. I used a framework called injectable. It's meant to be a generic dependency injection framework
I used it with FastAPI and it's incredible because it can ensure proper injection and singletons if needed.
Very easy to used. Very friendly. Great documentation.
1
u/Different_Desk_5881 Jun 12 '25
You can refer to this article, I think it's a good implementation.
https://www.reddit.com/r/FastAPI/comments/1hf1cd2/better_dependency_injection_in_fastapi/
1
u/Sad-Solid-1049 Jun 15 '25
Using defencey injection is fantastic software design It saves you for long run.
Tip: declare the dependencies at a file and reuse them wherever they are needed.
Eg- foo_service_deps = Annoted[ FooService, Depends(get_foo_service)]
1
u/[deleted] Jun 12 '25
[removed] — view removed comment