← Back to FastAPI, page 1

fastapi-0004 · Easy fresher

How do you accept a JSON request body in FastAPI using a Pydantic model?

Declare a class that inherits from pydantic.BaseModel and use it as a parameter type. FastAPI reads the JSON body, validates it against the model, and passes an instance to your function, returning 422 with details if validation fails. You can mix body, path and query parameters in one endpoint, and use model_dump() to turn the model into a dict.

Full answer

For POST, PUT and PATCH, data usually arrives as JSON in the request body. FastAPI uses Pydantic models to describe it:

python
class Admission(BaseModel):
    name: str
    age: int
    email: str | None = None
    subjects: list[str] = []
python
@app.post("/admissions", status_code=201)
def create_admission(admission: Admission): ...

What FastAPI does:

  1. Reads the body as JSON (if the body is not valid JSON, 422 with type json_invalid).
  2. Validates with Pydantic: required fields present, types correct. In the default "lax" mode Pydantic converts compatible values, such as "16" to 16, but rejects "sixteen".
  3. Passes an Admission instance; you use attributes like admission.name.
  4. Adds the model's JSON Schema to OpenAPI so /docs shows an example form.

Mixing sources in one endpoint:

python
@app.put("/classes/{class_id}/students")
def add(class_id: int, admission: Admission, notify: bool = False): ...

class_id from the path, notify from the query, admission from the body.

Useful extras:

  • admission.model_dump() gives a dict (Pydantic v2; v1 used .dict()).
  • Body(embed=True) expects {"admission": {...}} instead of the bare object.
  • Several model parameters make FastAPI expect a body with one key per parameter.
  • A single plain value in the body needs Body(): priority: Annotated[int, Body()].
  • Extra unknown fields are ignored by default. Set model_config = ConfigDict(extra="forbid") to reject them, which catches client typos.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict

app = FastAPI()


class Admission(BaseModel):
    model_config = ConfigDict(extra="forbid")

    name: str
    age: int
    email: str | None = None
    subjects: list[str] = []


@app.post("/classes/{class_id}/admissions", status_code=201)
def create_admission(class_id: int, admission: Admission, notify: bool = False):
    return {"class_id": class_id, "notify": notify, "data": admission.model_dump()}


c = TestClient(app)
r = c.post("/classes/9/admissions?notify=true", json={"name": "Aarav", "age": "16", "subjects": ["Maths"]})
print(r.status_code, r.json())

r = c.post("/classes/9/admissions", json={"name": "Diya", "age": "sixteen", "grade": "A"})
print(r.status_code, [(e["loc"], e["type"]) for e in r.json()["detail"]])

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): 201 {'class_id': 9, 'notify': True, 'data': {'name': 'Aarav', 'age': 16, 'email': None, 'subjects': ['Maths']}} 422 [(['body', 'age'], 'int_parsing'), (['body', 'grade'], 'extra_forbidden')]

Key points

  • BaseModel subclasses become JSON body parameters
  • Pydantic validates; failures return 422
  • Path, query and body can be combined
  • model_dump() replaces v1's dict()
  • extra='forbid' rejects unknown fields

Common mistakes

  • Using .dict() and .json() from Pydantic v1 instead of model_dump() and model_dump_json()
  • Sending a single value in the body without Body()
  • Assuming unknown fields cause an error by default
  • Reading request.json() manually instead of declaring a model

Follow-ups

  • What is the difference between lax and strict mode in Pydantic v2?
  • How would you accept a list of models in the body?
  • How do you add example values to the docs for a model?

Tips

  • Say where each parameter comes from in a mixed endpoint
  • Mention the v1 to v2 method renames
  • Bring up extra='forbid' as a practical safety net