Bird
0
0

Examine this FastAPI role check dependency and identify the mistake:

medium📝 Debug Q6 of 15
FastAPI - Authentication and Security
Examine this FastAPI role check dependency and identify the mistake:
async def check_admin(user: User = Depends(get_current_user)):
    if user.role != 'admin':
        return HTTPException(status_code=403)

@app.get('/admin')
async def admin_panel(dep=Depends(check_admin)):
    return {'msg': 'Welcome admin'}
AThe dependency should not be async when checking roles
BReturning HTTPException instead of raising it prevents proper error handling
CThe user role comparison should use '==' instead of '!='
DDepends should not be used inside the endpoint function signature
Step-by-Step Solution
Solution:
  1. Step 1: Understand HTTPException usage

    HTTPException must be raised, not returned.
  2. Step 2: Analyze the code

    Returning HTTPException object does not trigger FastAPI's error handling.
  3. Step 3: Correct approach

    Use raise HTTPException(status_code=403) to block access.
  4. Final Answer:

    Returning HTTPException instead of raising it prevents proper error handling -> Option B
  5. Quick Check:

    Always raise HTTPException, don't return it [OK]
Quick Trick: Raise exceptions, don't return them in dependencies [OK]
Common Mistakes:
MISTAKES
  • Returning HTTPException object instead of raising
  • Misusing async keyword in dependencies
  • Incorrect role comparison operators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes