Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Pydantic ConfigDict Extra Fields and Strict Mode

See how Pydantic ConfigDict's extra and strict settings control unknown fields and type coercion in Python models, with examples for API validation.

~4 min readPython
#Pydantic#ConfigDict#Extra Fields#Strict Mode
Illustration of Pydantic ConfigDict controlling extra fields and strict mode in Python models

Controlling how Pydantic models handle unexpected input is a core part of building robust validation. In Pydantic v2, the ConfigDict type centralizes model configuration options. Two settings that are frequently confused are extra and strict: extra decides what happens when input contains keys that are not declared fields, while strict decides whether declared fields accept values that need type coercion. They solve different problems, but they often appear together in validation settings.

What ConfigDict Controls in Pydantic

ConfigDict is a type that describes the keys accepted by model_config; it replaces the older Config class from Pydantic v1. The settings affect validation and serialization. For input handling, the relevant options are:

  • extra controls undeclared input keys.
  • strict controls whether declared fields require values to already match the expected type.

The key detail is that extra fields do not have a declared type, so strict mode applies to declared fields, not to extra values.

The extra Policy: allow, forbid, ignore

The extra setting accepts three string values:

  • ignore (default): Extra keys are silently ignored and not stored on the model instance.
  • allow: Extra keys are retained and available via model_extra.
  • forbid: Extra keys raise a ValidationError.

Here is a minimal example:

python
from pydantic import BaseModel, ConfigDict class IgnoreModel(BaseModel): model_config = ConfigDict(extra="ignore") name: str class AllowModel(BaseModel): model_config = ConfigDict(extra="allow") name: str class ForbidModel(BaseModel): model_config = ConfigDict(extra="forbid") name: str data = {"name": "Ada", "age": 37} print(IgnoreModel(**data)) # name='Ada' print(AllowModel(**data).model_extra) # {'age': 37} # ForbidModel(**data) raises ValidationError

The choice of policy depends on whether you want to be strict about the shape of incoming data. For APIs that consume external payloads, forbid catches typos and unexpected fields early. For internal tools where forward compatibility matters, ignore can prevent breaking changes when the producer adds fields.

Strict Mode and Extra Fields

Strict mode controls type coercion for declared fields. When strict=True, Pydantic does not coerce values from one type to another; for example, a string "123" will not be accepted for an int field. By contrast, non-strict mode attempts safe coercions such as string-to-int.

Strict mode does not change how extra fields are handled. With extra="allow", extra values are stored as passed because Pydantic has no declared type to validate or coerce them against. This is true regardless of strict mode. The practical interaction is that strict makes declared fields stricter, while extra determines whether undeclared keys are permitted at all.

Combining extra and strict: Realistic Scenarios

Consider an API that receives a known set of fields plus a dynamic set of additional metadata. If you want to keep the metadata but still enforce the declared fields strictly, the combination extra="allow" and strict=True does that.

python
from pydantic import BaseModel, ConfigDict class Event(BaseModel): model_config = ConfigDict(extra="allow", strict=True) name: str timestamp: int payload = {"name": "deploy", "timestamp": 1700000000, "meta": {"env": "prod"}} event = Event(**payload) print(event.timestamp) # 1700000000 print(event.model_extra) # {'meta': {'env': 'prod'}}

In this example, timestamp is declared as int and the input already contains an integer, so strict mode accepts it. If the payload contained "1700000000" as a string, validation would fail; strict mode would not coerce it to an integer. The extra meta field is stored in model_extra without validation or conversion.

Strict mode and the extra policy are independent: enabling strict=True does not turn on extra="forbid". The example above is strict about timestamp but still keeps the meta extra field.

On the other hand, if you need to enforce a strict schema for a public API, you might set extra="forbid" and strict=True to reject both unknown fields and type mismatches. That combination gives the strongest guarantee that data matches your contract.

Validation Errors and Debugging

When extra="forbid", Pydantic raises a ValidationError that includes Extra inputs are not permitted. For example:

python
from pydantic import BaseModel, ConfigDict, ValidationError class ForbidModel(BaseModel): model_config = ConfigDict(extra="forbid") name: str try: ForbidModel(**{"name": "Ada", "age": 37}) except ValidationError as e: print(e)

This is helpful during development because it immediately surfaces typos in client code or changes in the data contract.

Strict mode errors are different. They occur when a value's type does not match the declared type, and the message indicates the expected type versus the received type. When both strict=True and extra="forbid" are active, one payload can produce multiple errors. Use e.errors() to inspect the list of validation problems, and use model_extra to check what was actually stored when extra="allow" is enabled.

Maintainability Considerations

Validation semantics and maintainability should drive this decision. extra="allow" can hide contract drift because unknown fields are accepted even when your model does not define or validate them. It is useful when you do not need to process the extra data, but it can make upstream changes harder to notice.

extra="forbid" makes the contract explicit and fails fast, which is often preferable in production services. extra="ignore" is a middle ground: it allows forward compatibility without storing unexpected data. Strict mode should be used deliberately because it disables coercions that other parts of your system may rely on.

Choosing the Right Configuration for Your API

The right combination depends on the role of the model. For request validation in a public API, extra="forbid" and strict=False is a common starting point because it rejects unknown fields while still allowing reasonable coercions such as string-to-int conversion. For internal service-to-service communication where both sides are controlled, extra="forbid" and strict=True gives the strongest contract enforcement. For models that need to accept evolving payloads, such as webhook receivers, extra="ignore" or extra="allow" with strict=False provides flexibility.

When you choose extra="allow", remember that the extra fields are untyped and are not validated. If you need to validate those fields, define them explicitly in the model. Test your configuration with representative payloads to ensure it behaves as intended.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.