Consider this FastAPI endpoint with a custom error response model:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class ErrorResponse(BaseModel):
detail: str
@app.get("/items/{item_id}", responses={404: {"model": ErrorResponse}})
async def read_item(item_id: int):
if item_id != 42:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id, "name": "The Answer"}What will the client receive if they request /items/1?
from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI() class ErrorResponse(BaseModel): detail: str @app.get("/items/{item_id}", responses={404: {"model": ErrorResponse}}) async def read_item(item_id: int): if item_id != 42: raise HTTPException(status_code=404, detail="Item not found") return {"item_id": item_id, "name": "The Answer"}
Look at the ErrorResponse model and the detail field.
The custom error response model ErrorResponse defines a detail field. When the endpoint raises an HTTPException with status 404, FastAPI uses this model to format the response. So the client receives a JSON with {"detail": "Item not found"} and status code 404.
Which of the following code snippets correctly defines a custom error response model for a 400 error in FastAPI?
Remember to define the model before using it in the decorator.
In FastAPI, the Pydantic model must be defined before it is referenced in the responses parameter. Also, the status code keys in responses should be integers, not strings.
Given this code:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class ErrorResponse(BaseModel):
message: str
@app.get("/data", responses={404: {"model": ErrorResponse}})
async def get_data():
raise HTTPException(status_code=404, detail="Data missing")When requesting /data, the response JSON is {"detail": "Data missing"} instead of {"message": "Data missing"}. Why?
from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI() class ErrorResponse(BaseModel): message: str @app.get("/data", responses={404: {"model": ErrorResponse}}) async def get_data(): raise HTTPException(status_code=404, detail="Data missing")
Think about how FastAPI formats HTTPException responses by default.
FastAPI automatically returns the detail field from HTTPException as the JSON key detail. The custom error response model only documents the response schema but does not change the actual response keys unless you handle the exception yourself.
Analyze this FastAPI code:
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
app = FastAPI()
class ErrorResponse(BaseModel):
message: str
@app.exception_handler(KeyError)
async def key_error_handler(request: Request, exc: KeyError):
return JSONResponse(
status_code=400,
content={"message": f"Missing key: {exc.args[0]}"}
)
@app.get("/items/{item_id}")
async def read_item(item_id: int):
data = {"1": "apple", "2": "banana"}
return {"item": data[str(item_id)]}What will be the JSON response and status code if the client requests /items/3?
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from pydantic import BaseModel app = FastAPI() class ErrorResponse(BaseModel): message: str @app.exception_handler(KeyError) async def key_error_handler(request: Request, exc: KeyError): return JSONResponse( status_code=400, content={"message": f"Missing key: {exc.args[0]}"} ) @app.get("/items/{item_id}") async def read_item(item_id: int): data = {"1": "apple", "2": "banana"} return {"item": data[str(item_id)]}
Consider what happens when the key is missing in the dictionary and how the exception handler works.
Requesting /items/3 causes a KeyError because '3' is not in the dictionary. The custom exception handler catches this and returns a JSON response with the message and status code 400.
Choose the most accurate description of how custom error response models work in FastAPI.
Think about what FastAPI does automatically and what requires manual coding.
Custom error response models in FastAPI mainly document the expected error response schema for OpenAPI and client generation. They do not automatically change the response content unless you write custom exception handlers.