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?
"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".
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With