Bird
0
0

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?
Aasync def admin_token(token: str = Depends(oauth2_scheme)): if token.startswith('admin-'): return {"token": token} raise HTTPException(status_code=403, detail="Forbidden")
Basync def admin_token(token: str = Depends(oauth2_scheme)): if 'admin-' in token: return {"token": token} return {"error": "Forbidden"}
Casync def admin_token(token: str = Depends(oauth2_scheme)): if token == 'admin-': return {"token": token} raise HTTPException(status_code=401, detail="Unauthorized")
Dasync def admin_token(token: str): if token.startswith('admin-'): return {"token": token} raise HTTPException(status_code=403, detail="Forbidden")
Step-by-Step Solution
Solution:
  1. 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-').
  2. 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.
  3. Final Answer:

    Option A correctly implements the required logic -> Option A
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes