You send what looks like a perfectly good request to your FastAPI app and get back 422 Unprocessable Content with a JSON blob that seems to blame the universe. The good news: a 422 from FastAPI is almost never a mystery. The response body tells you exactly which field failed and where FastAPI looked for it. You just need to know how to read it.
I wrote a small booking API, sent it six broken requests with FastAPI 0.165.0 and Pydantic 2.13, and recorded the real responses. Here is what each one means and how to fix it.
The test app
from fastapi import FastAPI, Form
from pydantic import BaseModel
class Booking(BaseModel):
room_id: int
guest_name: str
nights: int = 1
app = FastAPI()
@app.post("/bookings")
def create_booking(booking: Booking):
return booking
@app.post("/search")
def search(term: str):
return {"term": term}
@app.post("/login")
def login(username: str = Form()):
return {"username": username}
A valid call such as {"room_id": 12, "guest_name": "Asha"} to /bookings returns 200 with nights filled in as 1. Everything below is a failure I triggered deliberately.
How to read the detail array
Every 422 from FastAPI's built-in validation has the same shape: a detail list where each item describes one problem.
{"detail": [{"type": "missing", "loc": ["body", "guest_name"], "msg": "Field required", "input": {"room_id": 12}}]}
-
locis the most important key. The first element says where FastAPI looked (body,query,path,headerorcookie), and the rest is the path to the field. -
typeis a machine-readable error code from Pydantic, such asmissingorint_parsing. -
msgis the human sentence. -
inputshows what FastAPI actually received for that location. This is the field people skip, and it is often the fastest clue.
Read loc first, then input. Most bugs reveal themselves right there.
Cause 1: a required field is missing
Request body: {"room_id": 12}
{"type": "missing", "loc": ["body", "guest_name"], "msg": "Field required", "input": {"room_id": 12}}
Straightforward: guest_name has no default, so it is required. Either send it, or give it a default in the model (guest_name: str | None = None) if it is genuinely optional.
Cause 2: the value has the wrong type
Request body: {"room_id": "twelve", "guest_name": "Asha"}
{"type": "int_parsing", "loc": ["body", "room_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "twelve"}
Note that Pydantic in its default mode would accept the string "12" and convert it. It rejects "twelve" because there is nothing to convert. When you see int_parsing, float_parsing or bool_parsing, look at what the client is serializing. Front-end form libraries that send every value as text are a common source.
Cause 3: you sent form data instead of JSON
With Python's requests or httpx, it is easy to type data= when you meant json=. The body is then URL-encoded:
{"type": "model_attributes_type", "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": "room_id=12&guest_name=Asha"}
The input value gives it away: room_id=12&guest_name=Asha is form encoding, not JSON. Switch the client to json=payload, or in JavaScript use JSON.stringify together with a Content-Type: application/json header.
Cause 4: JSON text without a JSON content type
This one is subtle. I sent the correct JSON string, but as raw content with no Content-Type: application/json header:
{"type": "model_attributes_type", "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": "{\"room_id\": 12, \"guest_name\": \"Asha\"}"}
Look at input again: it is a string that contains JSON, not a JSON object. FastAPI did not parse it as JSON because the request never said it was JSON. Set the header. This shows up a lot with hand-written fetch calls and some HTTP clients in other languages.
This behavior is deliberate and fairly recent. The FastAPI docs explain that, since version 0.132.0, JSON bodies are only parsed when a valid JSON Content-Type is present, because the strict check blocks a class of cross-site request forgery against unauthenticated local APIs. If you upgraded and old clients suddenly started getting 422s, this is the likely reason. You can restore the old behavior with FastAPI(strict_content_type=False), but fixing the client is the safer choice.
Cause 5: the endpoint expects a query parameter, not a body
Here the client posted {"term": "pool"} as JSON to /search:
{"type": "missing", "loc": ["query", "term"], "msg": "Field required", "input": null}
The first item of loc is query. FastAPI treats a plain str, int or similar function parameter as a query parameter, and a Pydantic model parameter as the request body. So /search?term=pool returns 200, while the JSON body is ignored. If you actually want term in the body, wrap it in a model or declare it as term: str = Body(embed=True), which accepts {"term": "pool"} (I checked that it returns 200).
It is an easy mistake to make, because the signature def search(term: str) on a POST route looks like it should accept a body.
Cause 6: the endpoint expects form fields
/login declares username: str = Form(). Posting JSON to it gives:
{"type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": null}
The location is body, but input is null, which means FastAPI looked for a form field and found none. Send application/x-www-form-urlencoded or multipart data, or change the endpoint to accept a JSON model. Remember that form handling needs the python-multipart package installed.
Log every 422 on the server without changing the response
When a mobile app or a partner integration is sending the bad requests, you need visibility on the server. FastAPI raises RequestValidationError for these cases, and the official docs show how to register your own handler and still reuse the default one. This version logs the problem and returns the exact same 422 response as before:
import logging
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.exception_handlers import request_validation_exception_handler
logger = logging.getLogger("api")
app = FastAPI()
@app.exception_handler(RequestValidationError)
async def log_validation_error(request: Request, exc: RequestValidationError):
logger.warning("422 on %s %s: %s", request.method, request.url.path, exc.errors())
return await request_validation_exception_handler(request, exc)
When I posted {"room_id": 1}, the log line was:
WARNING:api:422 on POST /bookings: [{'type': 'missing', 'loc': ('body', 'guest_name'), 'msg': 'Field required', 'input': {'room_id': 1}}]
Be careful in production: input can contain personal data or secrets that a client sent by mistake. Consider logging only loc and type.
A 30-second checklist
- Read
loc[0]: is FastAPI looking in the body, query, path, header or cookie, and is that where the client is sending the value? - Read
input: is it a dict, a string containing JSON, form encoding, ornull? - Check the client:
json=versusdata=, and theContent-Typeheader. - Check the endpoint signature: plain types become query parameters, Pydantic models become the body,
Form()expects form fields. - Use the interactive docs at
/docsto send a known-good request and compare it with what your client sends.
If FastAPI is still new to you, it helps to get comfortable with Python type hints first, because FastAPI uses them to decide where every parameter comes from. Our team covers that foundation in live Python classes for working developers, and then builds full APIs in a hands-on FastAPI program.
A 422 is FastAPI doing its job: rejecting data that does not match the contract you declared. Once you treat loc and input as a map, most of these errors take a minute to fix.
Written by the editorial team at Tutorials Mania.
Top comments (0)