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

Viewed 17770

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?

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
Related