InterviewHubPRO
Section Overview
Q43

Question 43 of 65

Part 4: Web Frameworks, APIs & FastAPI (41 - 55)

66%
Python & FastAPI•Part 4: Web Frameworks, APIs & FastAPI (41 - 55)

FastAPI Dependency Injection (`Depends()`):

In Simple Words: A declarative mechanism to inject shared resources (database sessions, authentication, configs) into route handlers with automatic lifecycle cleanup.

python
from fastapi import Depends, HTTPException

async def get_current_user(token: str):
    if token != "secret-token":
        raise HTTPException(status_code=401, detail="Invalid token")
    return {"user": "alice"}

@app.get("/profile")
async def read_profile(user: dict = Depends(get_current_user)):
    return user