You want to create a FastAPI endpoint that accepts a Bearer token and returns the token only if it starts with 'admin-'. Which code snippet correctly implements this?
hard📝 state output Q8 of 15
FastAPI - Authentication and Security
You want to create a FastAPI endpoint that accepts a Bearer token and returns the token only if it starts with 'admin-'. Which code snippet correctly implements this?
Step 1: Check dependency injection and token check
async def admin_token(token: str = Depends(oauth2_scheme)):
if token.startswith('admin-'):
return {"token": token}
raise HTTPException(status_code=403, detail="Forbidden") uses Depends(oauth2_scheme) and checks token.startswith('admin-').
Step 2: Validate error handling
async def admin_token(token: str = Depends(oauth2_scheme)):
if token.startswith('admin-'):
return {"token": token}
raise HTTPException(status_code=403, detail="Forbidden") raises HTTPException with 403 if token invalid, which is correct for forbidden access.
Final Answer:
Option A correctly implements the required logic -> Option A
Quick Check:
Use Depends + startswith + HTTPException 403 [OK]
Quick Trick:Use Depends and startswith, raise HTTPException for forbidden [OK]
Common Mistakes:
MISTAKES
Checking 'in' instead of startswith
Missing Depends() in parameter
Raising wrong HTTP status codes
Master "Authentication and Security" in FastAPI
9 interactive learning modes - each teaches the same concept differently