Core functionality for converting between Python objects and JSON-compatible data structures. Works with dataclasses, standard types, NamedTuples, NewTypes, and custom objects with extensive configuration options.
Convert JSON-like data to typed Python objects with automatic type inference, validation, and error reporting.
def deserialize(
type: AnyType,
data: Any,
*,
additional_properties: Optional[bool] = None,
aliaser: Optional[Aliaser] = None,
coerce: Optional[Union[bool, Callable]] = None,
conversion: Optional[AnyConversion] = None,
default_conversion: Optional[DefaultConversion] = None,
fall_back_on_default: Optional[bool] = None,
no_copy: Optional[bool] = None,
pass_through: Optional[CollectionOrPredicate[type]] = None,
schema: Optional[Schema] = None,
validators: Collection[Callable] = (),
) -> Any:
"""
Deserialize data into a typed Python object.
Parameters:
- type: Target type for deserialization
- data: Source data to deserialize (dict, list, primitive)
- additional_properties: Allow extra fields in objects (default: False)
- aliaser: Function to transform field names during deserialization
- coerce: Enable type coercion (e.g., string "123" to int 123)
- conversion: Custom conversion logic for this operation
- default_conversion: Default conversion strategy
- fall_back_on_default: Use field defaults when deserialization fails
- no_copy: Skip copying for performance (default: True)
- pass_through: Types to pass through without transformation
- schema: Schema metadata to apply during deserialization
- validators: Additional validation functions to apply
Returns:
Deserialized object of the specified type
Raises:
ValidationError: When data doesn't match type requirements
"""Convert typed Python objects to JSON-compatible data structures with control over field inclusion, formatting, and type handling.
def serialize(
type: AnyType,
obj: Any,
*,
additional_properties: Optional[bool] = None,
aliaser: Optional[Aliaser] = None,
check_type: Optional[bool] = None,
conversion: Optional[AnyConversion] = None,
default_conversion: Optional[DefaultConversion] = None,
exclude_defaults: Optional[bool] = None,
exclude_none: Optional[bool] = None,
exclude_unset: Optional[bool] = None,
fall_back_on_any: Optional[bool] = None,
no_copy: Optional[bool] = None,
pass_through: Optional[PassThroughOptions] = None,
) -> Any:
"""
Serialize a Python object to JSON-compatible data.
Parameters:
- type: Source type being serialized
- obj: Object to serialize
- additional_properties: Allow extra properties in output
- aliaser: Function to transform field names during serialization
- check_type: Validate object types during serialization
- conversion: Custom conversion logic for this operation
- default_conversion: Default conversion strategy
- exclude_defaults: Skip fields with default values
- exclude_none: Skip fields with None values
- exclude_unset: Skip unset fields (default: True)
- fall_back_on_any: Fall back to Any type handling when type checking fails
- no_copy: Skip copying for performance (default: True)
- pass_through: Configuration for pass-through serialization
Returns:
JSON-compatible data structure (dict, list, primitive)
"""Control which types are serialized without transformation for performance and compatibility.
@dataclass(frozen=True)
class PassThroughOptions:
"""
Configuration for pass-through serialization.
Attributes:
- any: Pass through Any-typed values
- collections: Pass through collection types
- dataclasses: Pass through dataclass instances
- enums: Pass through enum instances
- tuple: Pass through tuple instances
- types: Specific types or predicate function for pass-through
"""
any: bool = False
collections: bool = False
dataclasses: bool = False
enums: bool = False
tuple: bool = False
types: CollectionOrPredicate[AnyType] = ()from dataclasses import dataclass
from typing import Optional
from apischema import deserialize, ValidationError
@dataclass
class User:
id: int
name: str
email: Optional[str] = None
# Valid data
data = {"id": 1, "name": "John", "email": "john@example.com"}
user = deserialize(User, data)
print(user) # User(id=1, name='John', email='john@example.com')
# Missing optional field
data = {"id": 2, "name": "Jane"}
user = deserialize(User, data)
print(user) # User(id=2, name='Jane', email=None)
# Type coercion
data = {"id": "3", "name": "Bob"} # id as string
user = deserialize(User, data, coerce=True)
print(user) # User(id=3, name='Bob', email=None)# Validation errors with location information
try:
deserialize(User, {"id": "invalid", "name": 123})
except ValidationError as err:
for error in err.errors:
print(f"Field {error['loc']}: {error['err']}")
# Field ['id']: invalid literal for int() with base 10: 'invalid'
# Field ['name']: str expectedfrom dataclasses import dataclass, field
from typing import List
@dataclass
class Product:
id: int
name: str
price: float = 0.0
tags: List[str] = field(default_factory=list)
product = Product(id=1, name="Widget", tags=["electronics"])
# Default serialization
result = serialize(Product, product)
print(result) # {'id': 1, 'name': 'Widget', 'price': 0.0, 'tags': ['electronics']}
# Exclude default values
result = serialize(Product, product, exclude_defaults=True)
print(result) # {'id': 1, 'name': 'Widget', 'tags': ['electronics']}
# Exclude None values (when present)
product.price = None
result = serialize(Product, product, exclude_none=True)
print(result) # Excludes price field if Nonefrom apischema import alias, serialize, deserialize
@dataclass
class APIResponse:
user_id: int = field(metadata=alias("userId"))
full_name: str = field(metadata=alias("fullName"))
# JSON uses camelCase field names
data = {"userId": 123, "fullName": "John Doe"}
response = deserialize(APIResponse, data)
print(response) # APIResponse(user_id=123, full_name='John Doe')
# Serialize back to camelCase
result = serialize(APIResponse, response)
print(result) # {'userId': 123, 'fullName': 'John Doe'}from datetime import datetime
from typing import Dict, List
from uuid import UUID
@dataclass
class Order:
id: UUID
created_at: datetime
items: List[Dict[str, Any]]
metadata: Dict[str, str]
# Deserialize complex nested data
data = {
"id": "123e4567-e89b-12d3-a456-426614174000",
"created_at": "2023-01-15T10:30:00Z",
"items": [
{"product_id": 1, "quantity": 2, "price": 29.99}
],
"metadata": {"source": "web", "campaign": "sale2023"}
}
order = deserialize(Order, data)
print(order.id) # UUID object
print(type(order.created_at)) # datetime objectGenerate serialization and deserialization method functions for custom applications and reuse.
def deserialization_method(
type: AnyType,
*,
additional_properties: Optional[bool] = None,
aliaser: Optional[Aliaser] = None,
coerce: Optional[Union[bool, Callable]] = None,
conversion: Optional[AnyConversion] = None,
default_conversion: Optional[DefaultConversion] = None,
fall_back_on_default: Optional[bool] = None,
no_copy: Optional[bool] = None,
pass_through: Optional[CollectionOrPredicate[type]] = None,
schema: Optional[Schema] = None,
validators: Collection[Callable] = (),
) -> Callable[[Any], Any]:
"""
Generate a deserialization method function for the given type.
Returns a function that can deserialize data of the specified type.
Useful for pre-generating methods for performance or reuse.
"""
def serialization_method(
type: AnyType,
*,
additional_properties: Optional[bool] = None,
aliaser: Optional[Aliaser] = None,
check_type: Optional[bool] = None,
conversion: Optional[AnyConversion] = None,
default_conversion: Optional[DefaultConversion] = None,
exclude_defaults: Optional[bool] = None,
exclude_none: Optional[bool] = None,
exclude_unset: Optional[bool] = None,
fall_back_on_any: Optional[bool] = None,
no_copy: Optional[bool] = None,
pass_through: Optional[PassThroughOptions] = None,
) -> Callable[[Any], Any]:
"""
Generate a serialization method function for the given type.
Returns a function that can serialize objects of the specified type.
Useful for pre-generating methods for performance or reuse.
"""
def serialization_default(
*,
additional_properties: Optional[bool] = None,
aliaser: Optional[Aliaser] = None,
default_conversion: Optional[DefaultConversion] = None,
exclude_defaults: Optional[bool] = None,
exclude_none: Optional[bool] = None,
exclude_unset: Optional[bool] = None,
) -> Callable[[Any], Any]:
"""
Generate a default serialization method optimized for any object type.
Uses fall_back_on_any and pass_through options for maximum compatibility.
Useful as a general-purpose serializer for unknown object types.
"""AnyType = Any # Type alias for any type
Aliaser = Callable[[str], str] # Function type for field name transformation
CollectionOrPredicate = Union[Collection[T], Callable[[T], bool]] # Collection or predicate function