Python / FastAPI Interview Questions
How does FastAPI handle validation errors and how can you customise the error response format?
When a request fails Pydantic validation, FastAPI automatically returns a 422 Unprocessable Entity with a structured JSON body listing every field error. You can override this default behaviour with a custom exception handler.
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
app = FastAPI()
# Default 422 response body shape from FastAPI:
# {
# "detail": [
# {
# "type": "missing",
# "loc": ["body", "price"],
# "msg": "Field required",
# "input": {"name": "Widget"},
# "url": "https://errors.pydantic.dev/..."
# }
# ]
# }
# Custom error handler — reshape the response
@app.exception_handler(RequestValidationError)
async def custom_validation_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
errors = []
for error in exc.errors():
field = " -> ".join(str(loc) for loc in error["loc"])
errors.append({"field": field, "message": error["msg"]})
return JSONResponse(
status_code=422,
content={
"success": False,
"errors": errors,
},
)
class Product(BaseModel):
name: str = Field(min_length=1)
price: float = Field(gt=0)
stock: int = Field(ge=0)
@app.post("/products")
def create_product(product: Product):
return {"success": True, "product": product.model_dump()}
# Request: POST /products {}
# Custom response:
# {
# "success": false,
# "errors": [
# {"field": "body -> name", "message": "Field required"},
# {"field": "body -> price", "message": "Field required"},
# {"field": "body -> stock", "message": "Field required"}
# ]
# }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
