RequestValidationError

noun

say it: “rih-KWEST val-ih-DAY-shun AIR-er” /rɪˈkwɛst ˌvælɪˈdeɪʃən ˈɛrər/

The exception FastAPI raises when a request breaks its model's rules, before the route runs; its errors() list holds each problem, and a handler for it can reshape the 422 answer.

What is RequestValidationError in FastAPI?

RequestValidationError is the exception FastAPI raises before a route runs, when a request breaks its model's rules. Its errors() list is what the usual 422 answer reports; a handler for it can give that answer your API's own shape.

from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()

class TicketIn(BaseModel):
    bike: str
    problem: str

@app.exception_handler(RequestValidationError)
def validation_error(request: Request, exc: RequestValidationError):
    fields = [error["loc"][-1] for error in exc.errors()]
    return JSONResponse(status_code=422, content={"title": "Invalid ticket", "fields": fields})

@app.post("/tickets")
def create_ticket(ticket: TicketIn):
    return ticket

response = TestClient(app).post("/tickets", json={"bike": "Blue cruiser"})
print(response.status_code, response.json())   # 422 {'title': 'Invalid ticket', 'fields': ['problem']}

In a sentence

  • “A handler for RequestValidationError gave the bike shop's 422s the same shape as its 404s.”
  • “The empty body never reached the route: FastAPI raised RequestValidationError first.”

Level: Freelancer · More FastAPI terms at this level

Updated