Code Beautifier
Field required

Fix Pydantic "Field required"

Pydantic v2's error for a key missing from the input. Why fields without defaults are required, how to make one Optional, and how the generator decides.

Input that triggers it

[{"id": 1, "nickname": "countess"}, {"id": 2}]
Draft saved locally.

Local workspace

Named projects in IndexedDB · Local only — never synced to our servers. Worksp

Open manager

Batch workspace

Format multiple files locally in one run.

Style:
json
Pythonpython

What the error means

In Pydantic v2, a model field with no default value is required. If the input has no key for it, validation fails with Field required and the location of the missing field: nickname: Field required [type=missing, input_value={'id': 2}]. The error includes the input that was validated, which makes it easy to confirm the key really is absent rather than misspelled.

In the example, the first record has nickname and the second does not. A model generated from the first record alone requires nickname, and the second record fails.

Why it happens

  • The generation sample always had the key, so the field was emitted without a default.
  • The key is optional in the producer's contract — populated for some records, omitted for others.
  • An Optional[str] annotation without a default. Optional only says the value may be None; it does not make the key optional. nickname: Optional[str] still raises Field required when the key is absent. Only = None (or another default) does.
  • An alias mismatch: the JSON key is nick_name and the field is nickname with no alias, so the key is present but not recognised.

How to fix it

  1. Paste a sample that includes a record without the key into the generator above. It merges the records and emits nickname: Optional[str] = None for any field absent from at least one — the annotation and the default together are what make the key optional.
  2. In an existing model, add the default: nickname: Optional[str] = None, or nickname: str = "" if an empty string is the right meaning of "absent" in your domain.
  3. If the key uses a different name in the JSON, use Field(alias="nick_name") rather than renaming the attribute, and set model_config = ConfigDict(populate_by_name=True) if you also construct the model in code.
  4. If the key must always be present, the error is correct; fix the producer.

The model that accepts both records:

from typing import Optional
from pydantic import BaseModel

class Root(BaseModel):
    id: int
    nickname: Optional[str] = None

If it still fails

  • Pydantic reports every missing field in one pass, so a long list usually means the whole payload has a different shape — an array where an object was expected, or the object nested one level deeper.
  • kotlinx.serialization's MissingFieldException is the same rule with the same fix (a default); JSON to Kotlin applies it.
  • JSON Diff between a passing and a failing record lists the absent keys by path.

Related errors