Bird
0
0

Given this FastAPI code snippet, what will be the JSON response body when a 400 error occurs?

medium📝 component behavior Q4 of 15
FastAPI - Error Handling
Given this FastAPI code snippet, what will be the JSON response body when a 400 error occurs? ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel class ErrorResponse(BaseModel): detail: str app = FastAPI() @app.get("/items/{item_id}", responses={400: {"model": ErrorResponse}}) async def read_item(item_id: int): if item_id < 0: raise HTTPException(status_code=400, detail="Invalid item ID") return {"item_id": item_id} ```
A{"error": "Invalid item ID"}
B{"detail": "Invalid item ID"}
C{"message": "Invalid item ID"}
D{"detail": {"msg": "Invalid item ID"}}
Step-by-Step Solution
Solution:
  1. Step 1: Understand the error response model

    The ErrorResponse model has a single field detail of type string.
  2. Step 2: Match the raised HTTPException detail to the model

    The exception sets detail="Invalid item ID", which matches the detail field in the model.
  3. Final Answer:

    {"detail": "Invalid item ID"} -> Option B
  4. Quick Check:

    Error response matches model field 'detail' with exception detail [OK]
Quick Trick: Error response keys match Pydantic model fields exactly [OK]
Common Mistakes:
MISTAKES
  • Using wrong key names like 'error' or 'message'
  • Nesting detail inside another dictionary
  • Ignoring the model structure in response

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes