fepex65885
fepex65885

Reputation: 31

What are the advantages of using Depends in FastAPI?

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:

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.

Upvotes: 3

Views: 434

Answers (0)

Related Questions