Bird
0
0

Find the bug in this FastAPI code that tries to return a custom error response: ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel class ErrorResponse(BaseModel): message: str app = FastAPI() @app.get("/users/{user_id}", responses={404: {"model": ErrorResponse}}) async def get_user(user_id: int): if user_id == 0: return ErrorResponse(message="User not found") return {"user_id": user_id} ```

medium📝 Debug Q7 of 15
FastAPI - Error Handling
Find the bug in this FastAPI code that tries to return a custom error response: ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel class ErrorResponse(BaseModel): message: str app = FastAPI() @app.get("/users/{user_id}", responses={404: {"model": ErrorResponse}}) async def get_user(user_id: int): if user_id == 0: return ErrorResponse(message="User not found") return {"user_id": user_id} ```
AReturning ErrorResponse instance directly does not set HTTP status code 404.
BThe ErrorResponse model must have a 'detail' field, not 'message'.
CThe route decorator should use 'status_code=404' instead of 'responses'.
DThe function should raise HTTPException instead of returning a model.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the return statement for error case

    The function returns an instance of ErrorResponse but does not set the HTTP status code to 404.
  2. Step 2: Understand FastAPI error handling

    To send a 404 error, the function should raise HTTPException with status_code=404, not just return a model instance.
  3. Final Answer:

    Returning ErrorResponse instance directly does not set HTTP status code 404. -> Option A
  4. Quick Check:

    Return model != set HTTP error status; use HTTPException [OK]
Quick Trick: Raise HTTPException to send error status, not just return model [OK]
Common Mistakes:
MISTAKES
  • Returning error model instance without raising exception
  • Confusing field names in error model
  • Misusing 'status_code' parameter in decorator

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes