What are the advantages of using Depends in FastAPI?

81 Views Asked by At

I am studying the FastAPI framework and the principle of Dependency Injection, which is implemented in it using Depends. I have a question related to the expediency of using DI in those cases, which is given by well-known tutorials and examples from books.

For example, I have an endpoint handler function that uses dependency injection:

@app.get(
    '/something',
    status_code=status.HTTP_200_OK,
    response_model=SomeModel,
)
def get_something_endpoint(service = Depends(SomeService)) -> SomeModel:
    return service.get_something()

I can do the same without using DI:

@app.get(
    '/something',
    status_code=status.HTTP_200_OK,
    response_model=SomeModel,
)
def get_something_endpoint() -> SomeModel:
    return SomeService().get_something()

I don't understand why use DI in this case if it doesn't have any advantages in this simplest case:

  • If the service implementation changes, you will have to change the endpoint handler function. What difference does it make where to do it, in the arguments or in the body of the function?
  • The function actually gets a dependency automatically, it cannot be transferred from the outside, since the router connects directly to the FastAPI application.
  • Maybe this case is too trivial? Maybe it doesn't matter what exactly to use here, but more complex cases can show the full power of DI?

I suspect that I do not understand either some features of the DI principle or the implementation of Depends in FastAPI. Please explain where I am wrong.

I tried to look at the examples in the tutorials and the FastAPI documentation, but I did not find an answer to my question. The documentation suggests using DI, but doesn't seem to explain why.

0

There are 0 best solutions below