0
0
FastAPIframework~20 mins

Custom error response models in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
FastAPI Custom Error Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when a custom error response model is used in FastAPI?

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?

FastAPI
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"}
A{"error": "Item not found"} with status code 404
B{"detail": "Item not found"} with status code 404
C{"detail": "Not Found"} with status code 404
D{"message": "Item not found"} with status code 404
Attempts:
2 left
💡 Hint

Look at the ErrorResponse model and the detail field.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a custom error response model in FastAPI?

Which of the following code snippets correctly defines a custom error response model for a 400 error in FastAPI?

A
@app.get("/users/{user_id}", responses={400: {"model": ErrorModel}})
async def get_user(user_id: int):
    pass

class ErrorModel(BaseModel):
    error: str
B
class ErrorModel(BaseModel):
    error: str

@app.get("/users/{user_id}", responses={"400": {"model": ErrorModel}})
async def get_user(user_id: int):
    pass
C
@app.get("/users/{user_id}", responses={"400": {"model": ErrorModel}})
async def get_user(user_id: int):
    pass

class ErrorModel(BaseModel):
    error: str
D
class ErrorModel(BaseModel):
    error: str

@app.get("/users/{user_id}", responses={400: {"model": ErrorModel}})
async def get_user(user_id: int):
    pass
Attempts:
2 left
💡 Hint

Remember to define the model before using it in the decorator.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI custom error response model not show the expected field?

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?

FastAPI
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")
AThe custom error response model is ignored unless you manually catch the exception and return it.
BThe ErrorResponse model must have a 'detail' field to match the HTTPException detail key.
CFastAPI uses the HTTPException detail field as 'detail' key by default, ignoring the custom model's field name.
DThe responses dictionary must use string keys for status codes to work properly.
Attempts:
2 left
💡 Hint

Think about how FastAPI formats HTTPException responses by default.

state_output
advanced
2:00remaining
What is the output of this FastAPI endpoint with a custom error response model and manual exception handling?

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?

FastAPI
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)]}
A{"message": "Missing key: 3"} with status code 400
B{"detail": "KeyError"} with status code 400
C500 Internal Server Error with no JSON response
D{"item": null} with status code 200
Attempts:
2 left
💡 Hint

Consider what happens when the key is missing in the dictionary and how the exception handler works.

🧠 Conceptual
expert
2:00remaining
Which statement best describes the role of custom error response models in FastAPI?

Choose the most accurate description of how custom error response models work in FastAPI.

AThey serve primarily as documentation and validation for error responses, but actual response content depends on exception handling.
BThey automatically transform raised exceptions into JSON responses matching the model's fields without extra code.
CThey replace the default HTTPException behavior and require no manual exception handlers to customize error output.
DThey enforce that all error responses must have the exact fields defined in the model, or else FastAPI raises an error.
Attempts:
2 left
💡 Hint

Think about what FastAPI does automatically and what requires manual coding.