← Back to FastAPI, page 3

fastapi-0059 · Easy fresher

How do you read FastAPI's 422 validation error response, and what do loc, msg, type and input mean?

When request data fails validation, FastAPI returns 422 Unprocessable Entity with a JSON body {"detail": [ ... ]}. Each item has loc (where the problem is: body, query, path, header, cookie, followed by the field path), msg (human text), type (a stable machine code such as missing or int_parsing), and often input (the offending value) and ctx (constraint details). Clients should use loc and type, not parse msg.

Full answer

Example response for a bad body:

json
{"detail": [
  {"type": "missing", "loc": ["body", "name"], "msg": "Field required", "input": {...}},
  {"type": "int_parsing", "loc": ["body", "age"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "abc"}
]}

Reading each part:

  • loc: a path from the request source down to the field. The first element is the source: "body", "query", "path", "header" or "cookie". Nested models and lists extend it: ["body", "marks", 2, "score"] means the third item of marks. With a single non-embedded body model the model name is not part of loc.
  • type: stable codes from Pydantic v2 such as missing, string_too_short, greater_than_equal, int_parsing, literal_error, value_error, json_invalid. Use these in client logic and tests.
  • msg: English text; may change between versions.
  • input: the value received, helpful in development. Consider hiding it in production if it can include sensitive data (override the handler).
  • ctx: constraint values, e.g. {"min_length": 3}.

Notes:

  • Several errors are reported together, so a client can fix all fields in one round trip.
  • Malformed JSON gives json_invalid with a position in ctx.
  • Wrong types for path parameters are also 422, not 404.
  • Errors raised in your own code with HTTPException use {"detail": "text"} instead, so clients see two shapes unless you standardise (see custom exception handlers).
  • Response validation errors (your function returned bad data) are a server bug and result in a 500, not a 422.

Frontend tip: map loc[-1] to the form field name to show messages beside inputs.

python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field

app = FastAPI()


class Mark(BaseModel):
    subject: str
    score: int = Field(ge=0, le=100)


class Student(BaseModel):
    name: str = Field(min_length=3)
    marks: list[Mark]


@app.post("/students/{roll_no}")
def create(roll_no: int, student: Student, page: int = 1):
    return {"ok": True}


c = TestClient(app)
body = {"name": "Al", "marks": [{"subject": "Maths", "score": 90}, {"subject": "DBMS", "score": 120}]}
r = c.post("/students/abc?page=x", json=body)
print(r.status_code)
for e in r.json()["detail"]:
    print(e["loc"], e["type"], "|", e["msg"], "|", e.get("ctx"))
r = c.post("/students/1", content="{bad json", headers={"content-type": "application/json"})
print(r.json()["detail"][0]["type"], r.json()["detail"][0]["loc"])

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 422 ['path', 'roll_no'] int_parsing | Input should be a valid integer, unable to parse string as an integer | None ['query', 'page'] int_parsing | Input should be a valid integer, unable to parse string as an integer | None ['body', 'name'] string_too_short | String should have at least 3 characters | {'min_length': 3} ['body', 'marks', 1, 'score'] less_than_equal | Input should be less than or equal to 100 | {'le': 100} json_invalid ['body', 1]

Key points

  • 422 means the request failed validation; body is {'detail': [...]}
  • loc starts with the source: body, query, path, header or cookie
  • type is a stable machine code; msg is for people
  • All errors are reported together
  • HTTPException errors use a different shape unless standardised

Common mistakes

  • Parsing the msg text in client code
  • Assuming one error per response
  • Exposing input values that may contain sensitive data
  • Mixing the 422 list shape and HTTPException string shape without a standard

Follow-ups

  • How would you convert 422 errors into one error format?
  • How do you hide input in production?
  • Why is a bad path parameter a 422 rather than a 404?

Tips

  • Explain loc with a nested example
  • Say use type not msg
  • Mention both error shapes