← Back to FastAPI, page 3

fastapi-0052 · Easy fresher

What is the difference between required, optional and nullable fields in Pydantic v2 and FastAPI, and how did Optional change from v1?

In Pydantic v2 a field with no default is required, even if its type allows None. str | None means None is accepted but the key must still be supplied; str | None = None makes it both nullable and optional. In v1, Optional[str] implicitly gave a default of None, which no longer happens. FastAPI follows these rules for body fields and uses defaults to decide whether query parameters are required.

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?
DeclarationRequired?Accepts null?
x: stryesno
x: str | Noneyes (v2)yes
x: str = "a"nono
x: str | None = Nonenoyes

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=True drops 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 with None; send explicit null to clear a nullable field.
  • OpenAPI marks fields in required only if they have no default; nullable types appear as anyOf with null (or nullable in 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.

python
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