How to Fix 422 Unprocessable Entity Error in FastAPI
422 Unprocessable Entity error in FastAPI happens when the request data does not match the expected model or schema. To fix it, ensure your request body matches the Pydantic model exactly, including required fields and data types.Why This Happens
This error occurs because FastAPI uses Pydantic models to validate incoming request data. If the data sent by the client is missing required fields, has wrong types, or is malformed, FastAPI cannot process it and returns a 422 error.
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
The Fix
Make sure the client sends all required fields with correct types in the JSON body. For example, include both name as a string and price as a float. This matches the Item model FastAPI expects.
curl -X POST "http://localhost:8000/items/" -H "Content-Type: application/json" -d '{"name": "Apple", "price": 1.5}'
Prevention
To avoid 422 errors, always validate your request data before sending it. Use tools like JSON schema validators or client-side checks. Also, keep your Pydantic models updated and clear about which fields are required or optional.
Use FastAPI's automatic docs at /docs to test your API and see the expected request format.
Related Errors
Other common errors include:
- 400 Bad Request: Malformed JSON or invalid query parameters.
- 422 Validation Error: Similar to 422 Unprocessable Entity but often from query or path parameters.
- 500 Internal Server Error: Server-side bugs unrelated to request validation.