python
38 lines · 8 steps
Custom validation error responses in FastAPI
Override FastAPI's validation handler to return a clean, structured error payload with enum hints.
Explained by
highlit
1from enum import Enum
2from typing import Annotated
3
4from fastapi import FastAPI, Query, Request, status
5from fastapi.exceptions import RequestValidationError
6from fastapi.responses import JSONResponse
7
8app = FastAPI()
9
10
11class OrderStatus(str, Enum):
12 pending = "pending"
13 paid = "paid"
14 shipped = "shipped"
15 cancelled = "cancelled"
16
17
18@app.exception_handler(RequestValidationError)
19async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
20 errors = []
21 for err in exc.errors():
22 field = ".".join(str(loc) for loc in err["loc"][1:]) or str(err["loc"][0])
23 detail = {"field": field, "message": err["msg"], "type": err["type"]}
24 if err["type"] == "enum":
25 detail["allowed"] = err.get("ctx", {}).get("expected")
26 errors.append(detail)
27 return JSONResponse(
28 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
29 content={"errors": errors},
30 )
31
32
33@app.get("/orders")
34async def list_orders(
35 status: Annotated[OrderStatus | None, Query(description="Filter by order status")] = None,
36 limit: Annotated[int, Query(ge=1, le=100)] = 20,
37):
38 return {"status": status, "limit": limit, "items": []}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A single exception handler lets you reshape every validation error into a consistent client-facing format.
- 2String-backed enums let FastAPI both constrain input and expose the allowed values in error messages.
- 3Annotated with Query attaches constraints like ge and le so bad input is rejected before your handler runs.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/custom-validation-error-responses-in-fastapi-explained-python-a1a1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.