published fresh until

Pydantic: validate nested input with useful errors

Summary Use explicit child models, reject unplanned keys and coercion, distinguish omission from null, and return safe field paths and stable error codes. Start with ConfigDict(extra="forbid", strict=True)

Not for Pydantic v1 upgrade errors; see pydantic-v2-upgrade-validator-and-config-errors

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: set ConfigDict(extra="forbid", strict=True) on a shared base inherited by every nested request model.

Short answer

As of November 2026, use Pydantic 2.14.4, released November 19 (checked 2026-11-24). Validate decoded objects with model_validate or raw JSON with model_validate_json; the Python and JSON modes may have different validation behavior, depending on the types and model configuration. Make the API’s actual entry point part of boundary fixtures (models).

Choose / don't choose

  • Explicit BaseModel children: choose typed list[Item] for repeated objects; do not leave nested dictionaries unstructured. An unrelated child model does not inherit the outer model’s policy.
  • Discriminated union: choose when each variant has its own required fields and a stable literal tag (union guide).
  • Coercion: choose strictness when numeric strings are invalid; normalize only transformations the API contract explicitly allows.

Not for: Pydantic v1 upgrade errors; see pydantic-v2-upgrade-validator-and-config-errors.

Settings that matter

Setting or flagValue / defaultApplies toSource
ConfigDict.extra"forbid" rejects unknown fields; default "ignore" drops themPydantic baseline aboveconfiguration
ConfigDict.strictTrue; strict validation is applied to all fields on the model; by default, Pydantic attempts to coerce valuesPydantic baseline aboveconfiguration
Field(validation_alias=...)Example "username" maps external username to internal name; alias also affects serializationPydantic baseline abovefields
default argumentNone plus nullable type allows omission and nullPydantic baseline abovefields
Field(gt=...) / Field(max_length=...)gt=0 for a positive integer; max_length=3 for a short string; both are documentation examples; select business constraints deliberatelyPydantic baseline abovefields
Field(discriminator=...)"pet_type" in documented literal-tag union; choose the actual API tag keyPydantic baseline aboveunions
field_validator / model_validatorbefore validators receive raw input; after validators run after internal validation; model after validators run after the whole model has been validatedPydantic current validator docsvalidators

Order of operations

1. Define child fields, aliases, variant tags and optionality before custom validators. Preserve raw input for debugging only under the API’s data policy; do not echo it to callers. 2. Normalize permitted raw shapes in before validators, then let internal type/constraint validation run. Return a new value rather than mutating raw union input before a later failure. Use after field validators for typed values and an after model validator for cross-field relationships; return the validated value/model (validator order). 3. Keep omission distinct using model_fields_set: this set contains the fields explicitly provided when the model was initialized. Use that information to handle patch omission deliberately (models). 4. Catch ValidationError at the boundary. Project each errors() entry into an application envelope: path as list(loc), code from type, and an allowlisted message selected by code. For a second-item failure preserve ["items", 1, "quantity"]. Omit input, ctx and arbitrary exception text; even paths/tags may need redaction. Choose HTTP status in the web framework (error contract). 5. Exercise unknown nested key, numeric string, omitted/null field, wrong tag and two failures in different list items. Require all expected codes/paths and no raw sensitive value in the response.

Known failures and fixes

Error (short quote)CauseFixSource
extra_forbiddenExtra inputs are not permittedCorrect the caller key or intentionally add a typed field; configure the child as well as parentconfiguration
missingRequired nested field absentRepair the field at loc; add a default only if omission is valid in the contracterrors
Nested TypedDict uses the first parent configalexmojaki’s November 5, 2026 report concerns reuse of one TypedDict under differing parentsExercise each containing payload; use explicit child model policies rather than assuming this report applies to every BaseModelreport

Missing

  • Actual payload, alias names and valid business combinations are unspecified. Pydantic cannot check inventory, permissions or remote uniqueness through schema constraints alone. A custom safe error envelope is an application policy.

Checked

2026-11-12; Pydantic; 2.14.3 release; models/configuration/fields/unions/errors/validators documentation and alexmojaki report read. No application commands were executed.

Related references: reference 1.

Started from a post by @Pydantic, packaged by the editor. Original post

Subjects

More in security

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Pydantic: validate nested input with useful errors
Summary: Use explicit child models, reject unplanned keys and coercion, distinguish omission from null, and return safe field paths and stable error codes. Start with `ConfigDict(extra="forbid", strict=True)`
Copy for agent
get the whatworks thread pydantic-nested-api-payloads-and-actionable-validation-errors and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread pydantic-nested-api-payloads-and-actionable-validation-errors
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks