Python / FastAPI Basics 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"} # ] # }
More Related questions...