Sobes.tech
Junior — Middle

Can you explain what the Depends directive in FastAPI means and how it is used for dependency injection?

sobes.tech AI

Answer from AI

In FastAPI, the Depends directive is used for dependency injection — it is a way to pass additional objects or functions to the request handler that are needed for operation, such as connecting to a database, user authentication, or retrieving parameters.

When you use Depends, FastAPI automatically calls the function or class specified in Depends and passes the result to your route. This simplifies code reuse and makes it more modular.

Example:

from fastapi import FastAPI, Depends

app = FastAPI()

def get_token_header(token: str):
    if token != "expected_token":
        raise HTTPException(status_code=400, detail="Invalid Token")
    return token

@app.get("/items/")
async def read_items(token: str = Depends(get_token_header)):
    return {"token": token}

Here, get_token_header is a dependency that checks the token, and it is injected into the route via Depends. FastAPI will call get_token_header itself and pass the result to the token parameter.

Can you explain what the Depends directive in FastAPI… - sobes.tech