0
0
FastAPIframework~10 mins

Custom error response models in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the correct FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AFastAPI
BRequest
CResponse
DDepends
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI.
Trying to create app with a wrong class.
2fill in blank
medium

Complete the code to define a Pydantic model for error response with a message field.

FastAPI
from pydantic import BaseModel

class ErrorResponse([1]):
    message: str
Drag options to blanks, or click blank then click option'
ABaseModel
BModel
CErrorModel
DResponseModel
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong base class like Model or ResponseModel.
Forgetting to inherit from any class.
3fill in blank
hard

Fix the error in the route decorator to specify the response model for errors.

FastAPI
@app.get("/items/{item_id}", responses={404: {"model": [1])
async def read_item(item_id: int):
    return {"item_id": item_id}
Drag options to blanks, or click blank then click option'
AItem
BErrorResponse
CHTTPException
DResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong model name like Item or Response.
Using an instance instead of the class.
4fill in blank
hard

Fill both blanks to raise an HTTPException with a custom error response model.

FastAPI
from fastapi import HTTPException

if not item:
    raise HTTPException(status_code=[1], detail=[2])
Drag options to blanks, or click blank then click option'
A404
B"Item not found"
C"Invalid request"
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong status codes like 500 for not found.
Passing non-string detail values.
5fill in blank
hard

Fill all three blanks to define a route that returns a custom error response model on failure.

FastAPI
from fastapi import status

@app.get("/users/{user_id}", responses=[1]: {"model": [2])
async def get_user(user_id: int):
    if user_id != 1:
        raise HTTPException(status_code=[3], detail="User not found")
    return {"user_id": user_id}
Drag options to blanks, or click blank then click option'
Astatus.HTTP_404_NOT_FOUND
BErrorResponse
C404
Dstatus.HTTP_400_BAD_REQUEST
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing status codes like 400 and 404.
Using string '404' instead of status constants.