422 Unprocessable Entity
fastapi.exceptions.RequestValidationError
Stack trace
fastapi.exceptions.RequestValidationError: 1 validation error for Item body -> name field required (type=value_error.missing) During handling of the above exception, another exception occurred: fastapi.exceptions.RequestValidationError: 1 validation error for Item body -> name field required (type=value_error.missing)
Why it happens
FastAPI uses Pydantic models to validate incoming request bodies, query parameters, or path parameters. When the request data is missing required fields, has wrong types, or does not conform to the declared schema, FastAPI raises a 422 Unprocessable Entity error indicating validation failure.
Detection
Monitor your API logs for 422 responses and catch fastapi.exceptions.RequestValidationError exceptions in middleware or exception handlers to log detailed validation errors before returning responses.
Causes & fixes
Missing required fields in the JSON request body that the Pydantic model expects
Ensure the client sends all required fields exactly as defined in the Pydantic model, including correct field names and types.
Incorrect data types sent in the request, e.g., string instead of integer
Validate and convert client input before sending or update the Pydantic model to accept the correct types.
Sending form data or query parameters when the endpoint expects a JSON body
Use the correct Content-Type header (application/json) and send the data in the request body as JSON.
Pydantic model fields marked as required but the client sends null or omits them
Make fields optional with default values or Optional types if they are not always required, or enforce client to send them.
Code: broken vs fixed
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item):
return item
# Sending POST request without 'name' field triggers 422 error import os
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item):
return item
# Fixed by ensuring client sends JSON with all required fields including 'name'
# Example client payload: {"name": "Apple", "price": 1.5} Workaround
Catch RequestValidationError in a global exception handler, log the raw request body for debugging, and return a custom error message to clients while you fix the client payload.
Prevention
Use OpenAPI schema validation tools and client SDKs generated from FastAPI's schema to guarantee request payloads always conform to the expected Pydantic models.