Bird
0
0

Identify the error in this FastAPI code that attempts to use a custom error response model: ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel class ErrorModel(BaseModel): error: str app = FastAPI() @app.get("/items/{item_id}", responses={400: ErrorModel}) async def get_item(item_id: int): if item_id < 0: raise HTTPException(status_code=400, detail="Negative ID") return {"item_id": item_id} ```

medium📝 Debug Q6 of 15
FastAPI - Error Handling
Identify the error in this FastAPI code that attempts to use a custom error response model: ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel class ErrorModel(BaseModel): error: str app = FastAPI() @app.get("/items/{item_id}", responses={400: ErrorModel}) async def get_item(item_id: int): if item_id < 0: raise HTTPException(status_code=400, detail="Negative ID") return {"item_id": item_id} ```
AThe HTTPException detail must be an integer, not a string.
BThe ErrorModel class must inherit from BaseSettings, not BaseModel.
CThe 'responses' parameter should map status code to a dict with 'model' key.
DThe route decorator is missing the 'status_code' parameter.
Step-by-Step Solution
Solution:
  1. Step 1: Check the 'responses' parameter format

    FastAPI expects the 'responses' dict to map status codes to dicts with a 'model' key, not directly to a model class.
  2. Step 2: Identify the mistake

    The code uses responses={400: ErrorModel} instead of responses={400: {"model": ErrorModel}}.
  3. Final Answer:

    The 'responses' parameter should map status code to a dict with 'model' key. -> Option C
  4. Quick Check:

    Correct 'responses' syntax requires 'model' key [OK]
Quick Trick: Always wrap model in dict with 'model' key inside 'responses' [OK]
Common Mistakes:
MISTAKES
  • Assigning model class directly instead of dict
  • Confusing BaseModel with BaseSettings
  • Incorrect HTTPException detail type
  • Missing 'status_code' is not an error here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes