TypeAdapter
You may have types that are not BaseModels that you want to validate data against.
Or you may want to validate a List[SomeModel], or dump it to JSON.
For use cases like this, Pydantic provides TypeAdapter,
which can be used for type validation, serialization, and JSON schema generation without creating a
BaseModel.
A TypeAdapter instance exposes some of the functionality from
BaseModel instance methods for types that do not have such methods
(such as dataclasses, primitive types, and more):
from typing import List
from typing_extensions import TypedDict
from pydantic import TypeAdapter, ValidationError
class User(TypedDict):
name: str
id: int
UserListValidator = TypeAdapter(List[User])
print(repr(UserListValidator.validate_python([{'name': 'Fred', 'id': '3'}])))
#> [{'name': 'Fred', 'id': 3}]
try:
UserListValidator.validate_python(
[{'name': 'Fred', 'id': 'wrong', 'other': 'no'}]
)
except ValidationError as e:
print(e)
'''
1 validation error for list[typed-dict]
0.id
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='wrong', input_type=str]
'''
TypeAdapter can be used to apply the parsing logic to populate Pydantic models
in a more ad-hoc way. This function behaves similarly to
BaseModel.model_validate,
but works with arbitrary Pydantic-compatible types.
This is especially useful when you want to parse results into a type that is not a direct subclass of
BaseModel. For example:
from typing import List
from pydantic import BaseModel, TypeAdapter
class Item(BaseModel):
id: int
name: str
# `item_data` could come from an API call, eg., via something like:
# item_data = requests.get('https://my-api.com/items').json()
item_data = [{'id': 1, 'name': 'My Item'}]
items = TypeAdapter(List[Item]).validate_python(item_data)
print(items)
#> [Item(id=1, name='My Item')]
TypeAdapter is capable of parsing data into any of the types Pydantic can
handle as fields of a BaseModel.
Bases: Generic[T]
Type adapters provide a flexible way to perform validation and serialization based on a Python type.
A TypeAdapter instance exposes some of the functionality from BaseModel instance methods
for types that do not have such methods (such as dataclasses, primitive types, and more).
Note that TypeAdapter is not an actual type, so you cannot use it in type annotations.
The core schema for the type.
The schema validator for the type.
Type: SchemaValidator
The schema serializer for the type.
def validate_python(
__object: Any,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> T
Validate a Python object against the model.
T — The validated object.
The Python object to validate against the model.
Whether to strictly check types.
Whether to extract data from object attributes.
Additional context to pass to the validator.
def validate_json(
__data: str | bytes,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> T
Validate a JSON string or bytes against the model.
T — The validated object.
The JSON data to validate against the model.
Whether to strictly check types.
Additional context to use during validation.
def validate_strings(
__obj: Any,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> T
Validate object contains string data against the model.
T — The validated object.
The object contains string data to validate.
Whether to strictly check types.
Additional context to use during validation.
def get_default_value(
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Some[T] | None
Get the default value for the wrapped type.
Some[T] | None — The default value wrapped in a Some if there is one or None if not.
Whether to strictly check types.
Additional context to pass to the validator.
def dump_python(
__instance: T,
mode: Literal['json', 'python'] = 'python',
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> Any
Dump an instance of the adapted type to a Python object.
Any — The serialized object.
The Python object to serialize.
The output format.
Fields to include in the output.
Fields to exclude from the output.
Whether to use alias names for field names.
Whether to exclude unset fields.
Whether to exclude fields with default values.
Whether to exclude fields with None values.
Whether to output the serialized data in a way that is compatible with deserialization.
Whether to display serialization warnings.
def dump_json(
__instance: T,
indent: int | None = None,
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> bytes
Serialize an instance of the adapted type to JSON.
bytes — The JSON representation of the given instance as bytes.
The instance to be serialized.
Number of spaces for JSON indentation.
Fields to include.
Fields to exclude.
Whether to use alias names for field names.
Whether to exclude unset fields.
Whether to exclude fields with default values.
Whether to exclude fields with a value of None.
Whether to serialize and deserialize the instance to ensure round-tripping.
Whether to emit serialization warnings.
def json_schema(
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]
Generate a JSON schema for the adapted type.
dict[str, Any] — The JSON schema for the model as a dictionary.
Whether to use alias names for field names.
The format string used for generating $ref strings.
The generator class used for creating the schema.
The mode to use for schema generation.
@staticmethod
def json_schemas(
__inputs: Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]],
by_alias: bool = True,
title: str | None = None,
description: str | None = None,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]
Generate a JSON schema including definitions from multiple type adapters.
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue] — A tuple where:
- The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have JsonRef references to definitions that are defined in the second returned element.)
- The second element is a JSON schema containing all definitions referenced in the first returned element, along with the optional title and description keys.
__inputs : Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]]
Inputs to schema generation. The first two items will form the keys of the (first) output mapping; the type adapters will provide the core schemas that get converted into definitions in the output JSON schema.
Whether to use alias names.
The title for the schema.
The description for the schema.
The format string used for generating $ref strings.
The generator class used for creating the schema.