Bird
0
0

Identify the error in this FastAPI role check dependency:

medium📝 Debug Q14 of 15
FastAPI - Authentication and Security
Identify the error in this FastAPI role check dependency:
def check_admin(user: User = Depends(get_current_user)):
    if user.role == 'admin':
        return True
    else:
        return False

@app.get('/admin')
async def admin_panel(is_admin: bool = Depends(check_admin)):
    if not is_admin:
        raise HTTPException(status_code=403)
    return {"msg": "Welcome admin"}
ADependency should raise HTTPException directly, not return bool
BDepends should not be used inside dependency functions
CThe endpoint should not check is_admin, dependency handles it
DThe function should return user object, not bool
Step-by-Step Solution
Solution:
  1. Step 1: Analyze dependency behavior

    check_admin returns True/False instead of raising HTTPException on failure.
  2. Step 2: Understand best practice for RBAC in FastAPI

    Dependencies should raise HTTPException to stop execution early, not return bool flags.
  3. Final Answer:

    Dependency should raise HTTPException directly, not return bool -> Option A
  4. Quick Check:

    Raise exception in dependency, don't return bool [OK]
Quick Trick: Raise HTTPException in dependency to block access immediately [OK]
Common Mistakes:
MISTAKES
  • Returning bool instead of raising exception
  • Not stopping request early in dependency
  • Misusing Depends inside dependencies

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes