Bird
0
0

Analyze this FastAPI endpoint code:

medium📝 Debug Q7 of 15
FastAPI - Error Handling
Analyze this FastAPI endpoint code:
from fastapi import FastAPI, HTTPException
app = FastAPI()

@app.get("/users/{user_id}")
async def fetch_user(user_id: int):
    if user_id <= 0:
        raise HTTPException(status_code=400, detail="User ID must be positive")
    return {"user_id": user_id}
What is the issue with this code?
AThe endpoint should return 404 instead of 400 for invalid user_id.
BNo issue; it correctly raises HTTPException for invalid user_id.
CRaising HTTPException requires an additional 'headers' parameter.
DThe function should not be async when raising HTTPException.
Step-by-Step Solution
Solution:
  1. Step 1: Check validation logic

    The code raises a 400 Bad Request if user_id is zero or negative, which is appropriate.
  2. Step 2: Confirm HTTPException usage

    The HTTPException is raised correctly with status_code and detail.
  3. Step 3: Async function compatibility

    Using async does not affect raising exceptions; it is valid.
  4. Final Answer:

    No issue; it correctly raises HTTPException for invalid user_id. -> Option B
  5. Quick Check:

    Raising HTTPException with 400 on invalid input is correct [OK]
Quick Trick: Raising HTTPException with 400 on invalid input is correct [OK]
Common Mistakes:
MISTAKES
  • Thinking 404 is appropriate for invalid input
  • Believing async functions cannot raise HTTPException
  • Assuming headers parameter is mandatory

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes