← Back to FastAPI, page 4

fastapi-0062 · Easy fresher

What does ConfigDict do in a Pydantic v2 model, and how do extra='forbid', str_strip_whitespace, frozen and populate_by_name help in APIs?

model_config = ConfigDict(...) sets model-wide behaviour in Pydantic v2 (it replaces the v1 inner class Config). Useful options for APIs are extra="forbid" (reject unknown fields), str_strip_whitespace=True (trim strings), frozen=True (immutable, hashable instances), populate_by_name=True (accept both alias and field name), from_attributes=True (read ORM objects), and strict=True (no type coercion).

Full answer
python
class StudentIn(BaseModel):
    model_config = ConfigDict(extra="forbid", str_strip_whitespace=True, str_min_length=1)
    name: str
    roll_no: str = Field(alias="rollNo")

Options worth knowing:

  • extra: "ignore" (default; unknown keys are silently dropped), "forbid" (422 on unknown keys, which catches client typos like nmae), "allow" (keep extras; avoid for input models).
  • str_strip_whitespace, str_to_lower, str_to_upper, str_min_length: normalise strings before constraints are checked.
  • frozen=True: instances cannot be modified (raises on assignment) and become hashable; good for value objects and config.
  • populate_by_name=True (or validate_by_name in newer releases): accept roll_no as well as the alias rollNo.
  • from_attributes=True: validate from objects with attributes (ORM rows).
  • validate_assignment=True: re-validate when attributes are set after creation (small performance cost).
  • strict=True: no coercion: "17" is rejected for an int. Usually too strict for query strings and form data, but good for JSON-only internal APIs.
  • use_enum_values, json_schema_extra (add examples to the OpenAPI schema), alias_generator=to_camel (convert snake_case fields to camelCase JSON).
  • protected_namespaces: fields beginning with model_ trigger warnings, so rename them or configure it.

Share config via a base class (class APIModel(BaseModel): model_config = ConfigDict(...)) and inherit it, so every schema has the same behaviour. In v1 this was class Config:, which still works but is deprecated.

python
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from pydantic.alias_generators import to_camel


class APIModel(BaseModel):
    model_config = ConfigDict(extra="forbid", str_strip_whitespace=True, str_min_length=1,
                              alias_generator=to_camel, populate_by_name=True)


class StudentIn(APIModel):
    full_name: str
    roll_no: str = Field(pattern=r"^[A-Z]+-\d+$")


print(StudentIn.model_validate({"fullName": "  Asha Rao  ", "rollNo": "BCA-17"}))
print(StudentIn(full_name="Ravi", roll_no="BCA-2"))                 # populate_by_name allows Python names
print(StudentIn(full_name="Ravi", roll_no="BCA-2").model_dump(by_alias=True))

for bad in ({"fullName": "Asha", "rollNo": "BCA-1", "nmae": "typo"}, {"fullName": "   ", "rollNo": "BCA-1"}):
    try:
        StudentIn.model_validate(bad)
    except ValidationError as exc:
        print([(e["loc"], e["type"]) for e in exc.errors()])


class Point(BaseModel):
    model_config = ConfigDict(frozen=True)
    x: int
    y: int


p = Point(x=1, y=2)
print({p: "origin-ish"}[Point(x=1, y=2)])
try:
    p.x = 5
except ValidationError as exc:
    print(exc.errors()[0]["type"])


class Strict(BaseModel):
    model_config = ConfigDict(strict=True)
    age: int


try:
    Strict(age="17")
except ValidationError as exc:
    print(exc.errors()[0]["type"])

Standalone script. Run it with `python file.py`; it uses Pydantic only. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): full_name='Asha Rao' roll_no='BCA-17' full_name='Ravi' roll_no='BCA-2' {'fullName': 'Ravi', 'rollNo': 'BCA-2'} [(('nmae',), 'extra_forbidden')] [(('fullName',), 'string_too_short')] origin-ish frozen_instance int_type

Key points

  • model_config = ConfigDict(...) replaces v1 class Config
  • extra='forbid' catches unknown fields and client typos
  • str_strip_whitespace normalises input
  • frozen makes instances immutable and hashable
  • Share configuration through a base model

Common mistakes

  • Leaving extra at 'ignore' on input models and silently dropping typos
  • Using strict=True for query or form data where everything arrives as strings
  • Using the deprecated class Config in new code
  • Naming fields with a model_ prefix without configuring protected_namespaces

Follow-ups

  • How does alias_generator=to_camel help a JavaScript client?
  • What does validate_assignment cost?
  • When is frozen useful?

Tips

  • Name 5 options
  • Explain extra='forbid'
  • Mention the base-class pattern