response_model and 422 errors

Pydantic is useful at the edge in both directions. On the way in, it validates. On the way out, response_model coerces your return value into the shape you promised the client. If your handler returns extra fields, response_model strips them. If it returns the wrong type, you get a clear server-side error instead of a surprise in production.

router.py
python
from fastapi import APIRouter, HTTPException
from models import ProcessingStatus

@router.get("/status/{url:path}", response_model=ProcessingStatus)
async def get_processing_status(url: str):
    """Return the status of a previously submitted URL."""
    if url not in processing_status:
        raise HTTPException(status_code=404, detail="URL not found")
    return ProcessingStatus(**processing_status[url])

response_model=ProcessingStatus tells FastAPI to coerce the return value into a ProcessingStatus on the way out. The OpenAPI docs pick this up as the documented response shape.

A structured JSON object with a top-level detail array. Each entry lists the location of the error (body, query, path), the field name, the error type (missing, value_error, string_too_short), and a human-readable message. Clients can render the errors next to the offending form field. You never have to write the validator yourself.

422 response
json
{
  "detail": [
    {
      "loc": ["body", "character_age"],
      "msg": "ensure this value is less than or equal to 18",
      "type": "value_error.number.not_le"
    }
  ]
}

A typical 422 body. Pydantic builds this from the constraints on your Field declarations.

Quiz: Quiz

Loading practice…