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.Optionalonly says the value may beNone; it does not make the key optional.nickname: Optional[str]still raisesField requiredwhen the key is absent. Only= None(or another default) does. - An alias mismatch: the JSON key is
nick_nameand the field isnicknamewith noalias, so the key is present but not recognised.
How to fix it
- Paste a sample that includes a record without the key into the generator above. It merges the records and emits
nickname: Optional[str] = Nonefor any field absent from at least one — the annotation and the default together are what make the key optional. - In an existing model, add the default:
nickname: Optional[str] = None, ornickname: str = ""if an empty string is the right meaning of "absent" in your domain. - If the key uses a different name in the JSON, use
Field(alias="nick_name")rather than renaming the attribute, and setmodel_config = ConfigDict(populate_by_name=True)if you also construct the model in code. - 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
MissingFieldExceptionis 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
Input should be a valid integer
Match the annotation to the data: float for fractional values, str for codes, Optional[int] = None for nulls; use a validator or strict=False only when coercion is intended.
MissingFieldException: Field 'email' is required for type with serial name 'Root', but it was missing
Give the property a default (val email: String? = null), which the generator emits when any sample omits the key; or make the producer always send it.