fastapi.exceptions.RequestValidationError
fastapi.exceptions.RequestValidationError
Stack trace
fastapi.exceptions.RequestValidationError: 1 validation error for Request body -> json Expecting value: line 1 column 1 (char 0) (type=value_error.jsondecode)
Why it happens
FastAPI expects the request body to be valid JSON when the endpoint declares a JSON payload. If the client sends malformed JSON, empty body, or incorrect content-type headers, the JSON decoder raises this error.
Detection
Monitor for 422 HTTP responses with JSON decode errors in logs or middleware to catch malformed JSON requests before processing.
Causes & fixes
Client sends malformed or incomplete JSON in the request body
Ensure the client sends properly formatted JSON with correct syntax and no trailing commas or missing braces.
Request Content-Type header is missing or not set to 'application/json'
Set the Content-Type header to 'application/json' in the client request to inform FastAPI to parse the body as JSON.
Empty request body sent when JSON is expected
Send a valid JSON object or array in the request body; do not send empty body if the endpoint requires JSON.
Incorrect Pydantic model or missing required fields causing validation to fail after JSON decode
Verify the Pydantic model matches the expected JSON structure and all required fields are provided by the client.
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
# Client sends invalid JSON or missing Content-Type, triggers JSON decode 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
# Ensure client sends valid JSON with Content-Type: application/json header
# No code change needed server-side; fix client request Workaround
Add a middleware or exception handler to catch RequestValidationError, log the raw request body for debugging, and return a clear error message to the client.
Prevention
Use client-side JSON validation and always set Content-Type to 'application/json' when sending JSON payloads to FastAPI endpoints.