Bird
0
0

Why does this FastAPI code raise an error when handling Bearer tokens?

medium📝 Debug Q7 of 15
FastAPI - Authentication and Security
Why does this FastAPI code raise an error when handling Bearer tokens?
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/profile")
async def profile(token: str = Depends(oauth2_scheme)):
    if not token:
        return {"error": "No token"}
    return {"token": token}
AtokenUrl must be an absolute URL
BDepends() is missing around oauth2_scheme
CFunction must return JSONResponse explicitly
DOAuth2PasswordBearer raises HTTPException if token missing, so 'if not token' never runs
Step-by-Step Solution
Solution:
  1. Step 1: Understand OAuth2PasswordBearer behavior on missing token

    It automatically raises 401 error if token is missing, so code after does not run.
  2. Step 2: Analyze code logic

    The 'if not token' check is unreachable because missing token triggers exception first.
  3. Final Answer:

    OAuth2PasswordBearer raises HTTPException if token missing, so 'if not token' never runs -> Option D
  4. Quick Check:

    Missing token triggers exception before code runs [OK]
Quick Trick: OAuth2PasswordBearer auto-raises 401 on missing token [OK]
Common Mistakes:
MISTAKES
  • Expecting manual token check to run
  • Omitting Depends() (not the issue here)
  • Thinking tokenUrl must be full URL

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes