Full answer
Three independent ideas:
- Required or not: does a default exist?
- Nullable or not: may the value be
None? - Present or not: did the client send the key?
| Declaration | Required? | Accepts null? |
|---|---|---|
x: str | yes | no |
x: str | None | yes (v2) | yes |
x: str = "a" | no | no |
x: str | None = None | no | yes |
Migration trap: in Pydantic v1, x: Optional[str] silently meant = None. In v2, it is required, so old models that relied on this start rejecting payloads that omit the key. Write the default explicitly.
FastAPI effects:
- Query and header parameters: a default makes them optional; no default makes them required (422 if missing).
- Request bodies: missing required keys give 422 with
type: "missing". - Response models:
response_model_exclude_unset=Truedrops fields that were never set, which lets you distinguish "not provided" from "null". - PATCH updates: use
model_dump(exclude_unset=True)so omitted fields are not overwritten withNone; send explicitnullto clear a nullable field. - OpenAPI marks fields in
requiredonly if they have no default; nullable types appear asanyOfwithnull(ornullablein older OpenAPI 3.0 output).
For mutable defaults, use Field(default_factory=list). Pydantic copies simple mutable defaults per instance, but the factory form is clearer.
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class Student(BaseModel):
name: str
nickname: str | None # required, but None is allowed
email: str | None = None # optional and nullable
tags: list[str] = Field(default_factory=list)
@app.post("/students")
def create(s: Student):
return {"received": s.model_dump(), "set_by_client": sorted(s.model_fields_set)}
c = TestClient(app)
r = c.post("/students", json={"name": "Asha"})
print(r.status_code, [(e["loc"], e["type"]) for e in r.json()["detail"]])
print(c.post("/students", json={"name": "Asha", "nickname": None}).json())
print(c.post("/students", json={"name": "Asha", "nickname": "Ash", "email": None}).json())
props = c.get("/openapi.json").json()["components"]["schemas"]["Student"]
print("required in schema:", props["required"])
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 [(['body', 'nickname'], 'missing')] {'received': {'name': 'Asha', 'nickname': None, 'email': None, 'tags': []}, 'set_by_client': ['name', 'nickname']} {'received': {'name': 'Asha', 'nickname': 'Ash', 'email': None, 'tags': []}, 'set_by_client': ['email', 'name', 'nickname']} required in schema: ['name', 'nickname']
Key points
- No default means required, even if the type includes None
- str | None = None is optional and nullable
- v1 Optional implied a None default; v2 does not
- exclude_unset distinguishes omitted from null
- Use default_factory for mutable defaults
Common mistakes
- Assuming Optional[str] gives a default of None in v2
- Overwriting fields with None in PATCH because unset fields were dumped
- Using a mutable default such as [] outside Field(default_factory=...)
- Confusing missing keys with explicit null values
Follow-ups
- How do you distinguish a missing field from an explicit null?
- How does FastAPI decide if a query parameter is required?
- What does model_fields_set contain?
Tips
- Show the 2x2 of required and nullable
- Call out the v1 behaviour change
- Mention exclude_unset for PATCH