Bird
0
0

Identify the error in this FastAPI protected route code:

medium📝 Debug Q14 of 15
FastAPI - Authentication and Security
Identify the error in this FastAPI protected route code:
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def get_current_user(token: str):
    if token != "secret":
        raise HTTPException(status_code=401, detail="Unauthorized")
    return {"user": "admin"}

@app.get("/dashboard")
async def dashboard(user: dict = Depends(get_current_user)):
    return user
AOAuth2PasswordBearer is not imported
BHTTPException is not imported
CMissing Depends in get_current_user parameter
DRoute path is invalid
Step-by-Step Solution
Solution:
  1. Step 1: Check get_current_user parameter

    The function expects token: str but does not use Depends(oauth2_scheme) to get the token automatically.
  2. Step 2: Identify missing dependency injection

    Without Depends(oauth2_scheme), FastAPI won't provide the token, causing an error.
  3. Final Answer:

    Missing Depends in get_current_user parameter -> Option C
  4. Quick Check:

    Token param needs Depends(oauth2_scheme) [OK]
Quick Trick: Use Depends(oauth2_scheme) to get token in dependencies [OK]
Common Mistakes:
MISTAKES
  • Forgetting to import HTTPException
  • Not using Depends for token parameter
  • Incorrect route path syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes