Bird
0
0

You want to create a FastAPI endpoint that raises a 401 Unauthorized error only if the user token is missing or invalid. Which code snippet correctly uses HTTPException to do this?

hard🚀 Application Q8 of 15
FastAPI - Error Handling
You want to create a FastAPI endpoint that raises a 401 Unauthorized error only if the user token is missing or invalid. Which code snippet correctly uses HTTPException to do this?
Aif token is None: raise HTTPException(code=401, message="Unauthorized")
Bif token == False: raise HTTPException(status=401, detail="Unauthorized")
Cif not token: raise HTTPException(status_code=401, detail="Unauthorized")
Dif not token: return HTTPException(status_code=401, detail="Unauthorized")
Step-by-Step Solution
Solution:
  1. Step 1: Check correct condition and raising syntax

    Using if not token correctly checks missing or falsy token, and raising HTTPException with status_code and detail is correct.
  2. Step 2: Identify errors in other options

    Other options use wrong parameter names like code, message, or status, and one returns the exception instead of raising it.
  3. Final Answer:

    if not token: raise HTTPException(status_code=401, detail="Unauthorized") -> Option C
  4. Quick Check:

    Raise HTTPException with status_code and detail on missing token [OK]
Quick Trick: Raise HTTPException with status_code=401 for auth errors [OK]
Common Mistakes:
MISTAKES
  • Using wrong parameter names like code or status
  • Returning exception instead of raising it
  • Incorrect token check conditions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes