In Pydantic 2, when would you validate with a TypeAdapter instead of a BaseModel, and how should you create it?
answer
- validate a type, not a class
- a list of models
- schema built at construction
- create once, reuse
basics
~20 sUse a TypeAdapter in Pydantic 2 to validate a type that is not a BaseModel, such as list[LineItem], a union or a TypedDict. Building it compiles a schema, so create it once at module level and reuse it.
solid answer
~40 s`TypeAdapter(T)` gives any type Pydantic understands the model-style toolkit: `validate_python`, `validate_json`, `validate_strings`, `dump_python`, `dump_json` and `json_schema`. It suits a partner endpoint that posts a bare JSON array of line items, a `dict[str, int]`, a union, a TypedDict or a stdlib dataclass, where an envelope model would only exist to hold one field. Creating it **analyses the type into a core schema**, which has non-trivial cost, so build it once and reuse it. It raises the same `ValidationError` as a model. Two quirks: `dump_json` returns `bytes`, unlike `model_dump_json`, and a `config=` argument is refused for a type that carries its own config, such as a BaseModel. It is not a field annotation; use `RootModel` when you need an actual model class. It replaces version 1's `parse_obj_as`.
code
python · 22 linesfrom pydantic import BaseModel, TypeAdapter, ValidationError
class LineItem(BaseModel):
sku: str
quantity: int
LINE_ITEMS = TypeAdapter(list[LineItem]) # built once, at import time
items = LINE_ITEMS.validate_python([{'sku': 'S1', 'quantity': 2}])
print(items)
#> [LineItem(sku='S1', quantity=2)]
try:
LINE_ITEMS.validate_python([{'sku': 'S1', 'quantity': 2}, {'sku': 'S2'}])
except ValidationError as exc:
print([(e['loc'], e['type']) for e in exc.errors()])
#> [((1, 'quantity'), 'missing')]
print(LINE_ITEMS.dump_json(items))
#> b'[{"sku":"S1","quantity":2}]'go deeper
Recall that TypeAdapter validates types that are not models, such as a list of models, through validate_python and validate_json.
Explain the schema-building cost and why adapters are module-level constants, the bytes from dump_json, and the error locations that start at the list index.
Spot adapters rebuilt inside handlers in review, know when config is refused, and choose between TypeAdapter and RootModel for a reusable shape.
Decide where a codebase validates bare collections, adapters or wrapper models, so error shapes and schemas stay consistent across services.
## The problem it solves A `BaseModel` validates input into an instance of that class. Plenty of real input, though, is not shaped like one object with named fields: - a partner posts a **bare JSON array** of line items; - a cache returns a `dict[str, int]` of stock levels; - a message is one of several shapes, a **union**; - a payload is described by a `TypedDict` or a standard-library dataclass you do not want to convert into a model. Before version 2 you either wrapped these in a throwaway model with one field or called helper functions (`parse_obj_as`, `schema_of`). Pydantic 2 replaces both with **`TypeAdapter`**, a small object that brings model-style validation, serialization and JSON Schema to **any type Pydantic can handle as a field**. ## What a TypeAdapter offers | Method | Does | Notes | |---|---|---| | `validate_python(obj)` | validates Python data | the counterpart of `model_validate` | | `validate_json(data)` | parses and validates JSON | JSON input follows its own conversion rules | | `validate_strings(obj)` | validates string-only input | like `model_validate_strings` | | `dump_python(value)` | converts to Python data | | | `dump_json(value)` | converts to JSON | returns **`bytes`** | | `json_schema()` | produces a JSON Schema | | The `dump_json` return type is a deliberate inconsistency: `BaseModel.model_dump_json` returns `str` to stay compatible with version 1, while the newer `TypeAdapter` returns the `bytes` that are usually wanted anyway. Validation failures raise the same `ValidationError` a model raises, and error locations start at the adapter's top level. For `list[LineItem]` the first part of `loc` is the list index, so a missing quantity in the second item appears as `(1, 'quantity')`. ## Create it once Constructing a `TypeAdapter` makes Pydantic **analyse the type and build a core schema**, the compiled description that its validation engine executes. The documentation calls this overhead non-trivial and recommends creating an adapter for a given type **once** and reusing it in loops and hot paths. In practice: 1. Define adapters as module-level constants, next to the models they wrap. 2. Do not write `TypeAdapter(list[LineItem]).validate_python(data)` inside a request handler or a loop; that rebuilds the schema on every call. 3. For types with forward references, or ones expensive to build at import time, pass `config=ConfigDict(defer_build=True)` and the schema is built on first use (or when you call `rebuild()`, added in 2.10). ## Configuration rules `TypeAdapter` takes a `config=` argument, with two limits: - If the adapter **directly wraps** a type that has its own configuration (a `BaseModel`, a dataclass or a `TypedDict`), passing `config=` raises a `PydanticUserError`, because the setting would be silently ignored. Configure the model itself instead. - For a container such as `list[LineItem]`, the config applies to the adapter's own level, and the usual boundary still holds: it does not reach into `LineItem`, which keeps its own `model_config`. ## TypeAdapter versus RootModel Both validate a non-object top-level shape, but they serve different roles: - **`TypeAdapter`** is a tool you call. The documentation says it should not be used as a type annotation for a model's fields. - **`RootModel[list[LineItem]]`** is an actual model class with a `root` attribute. Use it when you need a class: to nest it in another model, give it methods, or pass it where a model is expected. ## Mistakes that show up in review 1. An adapter constructed inside a handler, a loop or a helper called per message, paying the schema build every time. 2. A `TypeAdapter` instance used as a field annotation in a model, where a `RootModel` or the plain type belongs. 3. `config=` passed to an adapter over a model, expecting it to change the model's behaviour; Pydantic refuses it. 4. Code that treats `dump_json` output as text and concatenates it with strings, then fails on `bytes`. 5. A one-field envelope model created only so a bare list can be validated, which then leaks into schemas and error messages. ## When a model is still the better choice - The data is one object with named fields: write a `BaseModel`. - You want methods, validators on the whole object or a named class in error messages and schemas: write a model. - You only need to check a shape once, at a boundary, and hand the result on as plain lists, dicts or existing models: an adapter is the lighter tool.
- In Pydantic 2, why does `TypeAdapter(Order, config=ConfigDict(strict=True))` raise an error?Order is a BaseModel and carries its own configuration, so a config passed to the adapter would not override it and would be silently ignored. Pydantic raises a PydanticUserError instead. Put the setting in Order's `model_config`, or pass `strict=True` to the individual validation call.
- In Pydantic 2, when would you pick `RootModel[list[LineItem]]` over `TypeAdapter(list[LineItem])`?When you need a real model class: to use it as a field type in another model, attach methods or validators to it, or pass it where code expects a BaseModel. A TypeAdapter is a validation tool, not a type, and should not be used as a field annotation.
- A TypeAdapter can be used as a field annotation inside a BaseModel.
- Building a TypeAdapter per request costs nothing.
- TypeAdapter's dump_json returns a str, like model_dump_json.
- Validating a list of models requires a wrapper model with an items field.
- Passing config to TypeAdapter(Order) overrides Order's model_config.
Assumes Pydantic 2; TypeAdapter is new in version 2 and replaces version 1's parse_obj_as and schema_of, which are deprecated.