Complete worked example
python
import json
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, ValidationError
class Identity(BaseModel):
model_config = ConfigDict(extra="forbid", validate_by_alias=True,
validate_by_name=True)
display_name: str = Field(validation_alias="displayName",
serialization_alias="name")
def inspect_example(payload):
try:
value = Identity.model_validate_json(json.dumps(payload))
return {"value": value.model_dump(by_alias=True)}
except ValidationError as error:
return {"error": sorted({e["type"] for e in error.errors()})}- Reasoning
- The example validates JSON using explicit configuration and then dumps with by_alias=True. A client can submit displayName or the permitted internal spelling and receives the same public name field. An unexpected admin key fails extra="forbid" even though the known display name itself is valid. Current Pydantic 2.14 patch releases tightened handling of alias-related extra input, including security fixes in 2.14.2. The local lab uses 2.14.3 and tests the actual configured behavior. Conflicting submitted aliases should not be treated as a trustworthy way to select an internal value or as a reason to silently widen the writable shape.