Sobes.tech
Junior — Middle

Can you give an example of dependency usage in FastAPI?

sobes.tech AI

Answer from AI

In FastAPI, dependencies are used to inject reusable components, such as database connections, authentication, or common configurations.

Example: a function that returns the current user can be a dependency for different routes.

from fastapi import FastAPI, Depends, HTTPException

app = FastAPI()

def get_current_user(token: str):
    if token != "secret-token":
        raise HTTPException(status_code=401, detail="Invalid token")
    return "user123"

@app.get("/profile")
async def read_profile(current_user: str = Depends(get_current_user)):
    return {"user": current_user}

Here, Depends allows get_current_user to be called automatically and its result passed to the handler.