How does FastAPI handle request validation and error responses?
Answer
FastAPI uses Pydantic for automatic request validation at every layer. When validation fails, FastAPI returns a 422 Unprocessable Entity response with a detailed JSON body listing every validation error — field name, location (body/path/query), error type, and message. This is automatic — no manual validation code needed. Example error: {"detail": [{"loc": ["body", "age"], "msg": "value is not a valid integer", "type": "type_error.integer"}]}. For custom HTTP errors, raise HTTPException: from fastapi import HTTPException; raise HTTPException(status_code=404, detail='User not found'). Create custom exception handlers: @app.exception_handler(CustomError) async def handler(request, exc): return JSONResponse(status_code=400, content={'error': str(exc)}). FastAPI's validation layer is one of its biggest productivity advantages.