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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)