Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of using Depends in FastAPI over just calling a dependent function/class?

FastAPI provides a way to manage dependencies, like DB connection, via its own dependency resolution mechanism.

It resembles a pytest fixture system. In a nutshell, you declare what you need in a function signature, and FastAPI will call the functions(or classes) you mentioned and inject the correct results when the handler is called.

Yes, it does caching(during the single handler run), but can't we achieve the same thing using just @lru_cache decorator and simply calling those dependencies on each run? Am I missing something?

like image 605
Ojomio Avatar asked May 18 '20 13:05

Ojomio


People also ask

What are dependencies in FastAPI?

"Dependency Injection" means, in programming, that there is a way for your code (in this case, your path operation functions) to declare things that it requires to work and use: "dependencies".

What is dependency injection stack overflow?

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.

What is dependency injection in Python?

Dependency injection is a technique built on the top of the Inversion of Control. The main idea is to separate the construction and usage of objects. As a software engineer, your objective is to build software so that it is modular and easy to extend.

Why use FastAPI depends?

FastAPI will also inject parameters from the request into your dependencies, and include them into the OpenApi specification. This allows you to re-use parameters, which can help you write less code, especially if your project grows large.


1 Answers

FastAPI will also inject parameters from the request into your dependencies, and include them into the OpenApi specification.

This allows you to re-use parameters, which can help you write less code, especially if your project grows large.

Without the dependency injection you'd have to specify the parameters on every route, every time.

In this example from the FastAPI docs we have common search parameters being shared.

async def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
    return commons
like image 172
Gabriel Cappelli Avatar answered Sep 23 '22 16:09

Gabriel Cappelli