Dependency declaration is ugly

Is it just me who dislikes the way dependencies are declared in FastAPI? Why does dependency injection have to be tied to type definitions?

It feels ironic that the primary reason for moving external dependencies into function arguments is to decouple them, yet declaring dependencies in the function's type signature ends up coupling them again in another way.

Does anyone else find this approach awkward?

7 comments · 81% upvoted · other discussions

comments

websvc

Maybe because they actually have a... type? Probably just you

pint

that is not dependency injection. it is just code reuse. separation of concepts, centralization of common logic.

devlittle

yeah, just you

WestRiverCS

I'm not sure if you have confronted the exact same issue that I have, but I'm glad I'm not the only one with this unpopular opnion... I kinda worked arond this, being tied to type definitions, by implementing my own class-based views and using starlette state.

BlackDereker

How else would the application know which class to instantiate when the route is called?

tuple32 [OP]

What’s the alternative? I think would be better to figure out a way to annotate or decorate the class or function that provides the dependencies. Then the injection will happen automatically whenever you declare an input with that type