CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-msrest

AutoRest swagger generator Python client runtime for REST API clients with serialization, authentication, and request handling.

Pending
Overview
Eval results
Files

serialization.mddocs/

Serialization

Robust serialization and deserialization system supporting complex data types, XML/JSON formats, date/time handling, custom model classes, and comprehensive validation. The serialization system converts between Python objects and REST API wire formats while maintaining type safety and validation.

Capabilities

Serialization

Convert Python objects to REST API formats (JSON/XML) with comprehensive type support.

class Serializer:
    def __init__(self, classes=None):
        """
        Initialize serializer with optional model classes.
        
        Parameters:
        - classes: Dict of model classes for complex type serialization
        """
    
    basic_types: dict = {str: 'str', int: 'int', bool: 'bool', float: 'float'}
    client_side_validation: bool = True
    
    def body(self, data, data_type: str, **kwargs):
        """
        Serialize data for request body.
        
        Parameters:
        - data: Python object to serialize
        - data_type: Target data type string
        - kwargs: Serialization options (is_xml, etc.)
        
        Returns:
        Serialized data (dict for JSON, ET.Element for XML)
        
        Raises:
        SerializationError if serialization fails
        ValidationError if data is None for required field
        """
    
    def url(self, name: str, data, data_type: str, **kwargs) -> str:
        """
        Serialize data for URL path parameters.
        
        Parameters:
        - name: Parameter name for error reporting
        - data: Data to serialize
        - data_type: Target type ('str', 'int', 'bool', etc.)
        - kwargs: Options (skip_quote for no URL encoding)
        
        Returns:
        URL-encoded string
        """
    
    def query(self, name: str, data, data_type: str, **kwargs) -> str:
        """
        Serialize data for URL query parameters.
        
        Parameters:
        - name: Parameter name
        - data: Data to serialize
        - data_type: Target type or array type like '[str]'
        - kwargs: Options (skip_quote for no URL encoding)
        
        Returns:
        Query parameter string
        """
    
    def header(self, name: str, data, data_type: str, **kwargs) -> str:
        """
        Serialize data for HTTP headers.
        
        Parameters:
        - name: Header name
        - data: Data to serialize
        - data_type: Target type
        - kwargs: Serialization options
        
        Returns:
        Header value string
        """
    
    def serialize_data(self, data, data_type: str, **kwargs):
        """
        Core serialization method handling all data types.
        
        Parameters:
        - data: Data to serialize
        - data_type: Target type string
        - kwargs: Serialization options
        
        Returns:
        Serialized data
        """
    
    def serialize_iter(self, data, iter_type: str, **kwargs):
        """
        Serialize iterables (lists, sets, etc.) with XML support.
        
        Parameters:
        - data: Iterable to serialize
        - iter_type: Item type string
        - kwargs: Options including XML configuration
        
        Returns:
        Serialized iterable
        """
    
    def serialize_dict(self, data, dict_type: str, **kwargs):
        """
        Serialize dictionaries with XML support.
        
        Parameters:
        - data: Dictionary to serialize
        - dict_type: Value type string
        - kwargs: Options including XML configuration
        
        Returns:
        Serialized dictionary
        """
    
    def serialize_object(self, data, object_type: str, **kwargs):
        """
        Serialize complex objects/models.
        
        Parameters:
        - data: Object to serialize
        - object_type: Object type string
        - kwargs: Serialization options
        
        Returns:
        Serialized object
        """
    
    def serialize_enum(self, data, enum_obj=None):
        """
        Serialize enum values.
        
        Parameters:
        - data: Enum value to serialize
        - enum_obj: Optional enum class for validation
        
        Returns:
        Serialized enum value
        """

Deserialization

Convert REST API responses back to Python objects with type inference and validation.

class Deserializer:
    def __init__(self, classes=None):
        """
        Initialize deserializer with model classes.
        
        Parameters:
        - classes: Dict of model classes for complex type deserialization
        """
    
    basic_types: dict = {str: 'str', int: 'int', bool: 'bool', float: 'float'}
    additional_properties_detection: bool = True
    key_extractors: list
    
    def __call__(self, target_obj: str, response_data, content_type=None):
        """
        Deserialize response data to target object type.
        
        Parameters:
        - target_obj: Target class name or type
        - response_data: Raw response data
        - content_type: Response content type
        
        Returns:
        Deserialized Python object
        
        Raises:
        DeserializationError if deserialization fails
        """
    
    def failsafe_deserialize(self, target_obj: str, data, content_type=None):
        """
        Deserialize with error tolerance for error handling scenarios.
        
        Parameters:
        - target_obj: Target object type
        - data: Response data
        - content_type: Content type hint
        
        Returns:
        Deserialized object or None if deserialization fails
        """
    
    def deserialize_data(self, data, data_type: str):
        """
        Core deserialization method handling all data types.
        
        Parameters:
        - data: Data to deserialize
        - data_type: Target type string
        
        Returns:
        Deserialized Python object
        """
    
    def deserialize_iter(self, data, iter_type: str):
        """
        Deserialize iterables from JSON arrays or XML.
        
        Parameters:
        - data: Iterable data to deserialize
        - iter_type: Item type string
        
        Returns:
        List of deserialized items
        """
    
    def deserialize_dict(self, data, dict_type: str):
        """
        Deserialize dictionaries from JSON objects or XML.
        
        Parameters:
        - data: Dict data to deserialize
        - dict_type: Value type string
        
        Returns:
        Dictionary with deserialized values
        """
    
    def deserialize_object(self, data, object_type: str):
        """
        Deserialize complex objects/models.
        
        Parameters:
        - data: Object data to deserialize
        - object_type: Target object type
        
        Returns:
        Deserialized model instance
        """
    
    def deserialize_enum(self, data, enum_obj):
        """
        Deserialize enum values with comprehensive handling.
        
        Parameters:
        - data: Enum data to deserialize
        - enum_obj: Enum class for validation
        
        Returns:
        Enum value or string if enum doesn't match
        """

Model Base Class

Base class for request/response model objects with serialization and validation support.

class Model:
    _attribute_map: dict = {}
    _validation: dict = {}
    _subtype_map: dict = {}
    
    def __init__(self, **kwargs):
        """
        Initialize model with keyword arguments.
        
        Parameters:
        - kwargs: Model field values
        """
    
    def validate(self) -> list:
        """
        Validate model recursively.
        
        Returns:
        List of ValidationError objects (empty if valid)
        """
    
    def serialize(self, keep_readonly=False, **kwargs) -> dict:
        """
        Serialize model to JSON-compatible dict.
        
        Parameters:
        - keep_readonly: Include readonly fields
        - kwargs: Serialization options (is_xml, etc.)
        
        Returns:
        JSON-compatible dictionary
        """
    
    def as_dict(self, keep_readonly=True, key_transformer=None, **kwargs) -> dict:
        """
        Convert model to dictionary with custom key transformation.
        
        Parameters:
        - keep_readonly: Include readonly fields
        - key_transformer: Function to transform keys
        - kwargs: Serialization options
        
        Returns:
        Dictionary representation
        """
    
    def __eq__(self, other) -> bool:
        """Compare models for equality."""
    
    def __ne__(self, other) -> bool:
        """Compare models for inequality."""
    
    def __str__(self) -> str:
        """String representation of model."""
    
    def is_xml_model(self) -> bool:
        """Check if model supports XML serialization."""
    
    @classmethod
    def deserialize(cls, data: str, content_type=None):
        """
        Parse string data to create model instance.
        
        Parameters:
        - data: JSON/XML string data
        - content_type: Data format ('application/json' or 'application/xml')
        
        Returns:
        Model instance
        
        Raises:
        DeserializationError if parsing fails
        """
    
    @classmethod
    def from_dict(cls, data: dict, key_extractors=None, content_type=None):
        """
        Create model instance from dictionary.
        
        Parameters:
        - data: Dictionary data
        - key_extractors: List of key extraction functions
        - content_type: Content type hint
        
        Returns:
        Model instance
        """
    
    @classmethod
    def enable_additional_properties_sending(cls):
        """Enable serialization of additional properties."""

Utility Classes

Timezone and datetime utility classes for proper date/time handling.

class UTC:
    """UTC timezone implementation."""
    
    def utcoffset(self, dt):
        """Return UTC offset (always zero)."""
    
    def tzname(self, dt):
        """Return timezone name."""
    
    def dst(self, dt):
        """Return daylight saving time offset."""

class _FixedOffset:
    """Fixed UTC offset timezone."""
    
    def __init__(self, offset_hours: int, name: str):
        """Initialize with hour offset and name."""
    
    def utcoffset(self, dt):
        """Return the fixed UTC offset."""
    
    def tzname(self, dt):
        """Return timezone name."""
    
    def dst(self, dt):
        """Return DST offset (always zero for fixed offset)."""

Key Extractors

Functions for extracting and transforming dictionary keys during deserialization.

def rest_key_extractor(attr: str, attr_desc: dict, data: dict):
    """
    Extract REST API key from response data.
    
    Parameters:
    - attr: Attribute name
    - attr_desc: Attribute description from _attribute_map
    - data: Response data dictionary
    
    Returns:
    Extracted key or KeyError
    """

def rest_key_case_insensitive_extractor(attr: str, attr_desc: dict, data: dict):
    """Case-insensitive REST key extraction."""

def last_rest_key_extractor(attr: str, attr_desc: dict, data: dict):
    """Extract last matching REST key."""

def xml_key_extractor(attr: str, attr_desc: dict, data):
    """
    Extract keys from XML data with namespace support.
    
    Supports XML attributes, elements, text content, and namespaces.
    """

def attribute_key_extractor(attr: str, attr_desc: dict, data: dict):
    """Extract using Python attribute names."""

def attribute_key_case_insensitive_extractor(attr: str, attr_desc: dict, data: dict):
    """Case-insensitive attribute key extraction."""

Data Type Support

Comprehensive support for various data types including dates, times, binary data, and collections.

# Static serialization methods
@staticmethod
def serialize_iso(attr, **kwargs) -> str:
    """Serialize datetime to ISO-8601 string."""

@staticmethod
def serialize_rfc(attr, **kwargs) -> str:
    """Serialize datetime to RFC-1123 string."""

@staticmethod
def serialize_unix(attr, **kwargs) -> int:
    """Serialize datetime to Unix timestamp."""

@staticmethod
def serialize_date(attr, **kwargs) -> str:
    """Serialize date to ISO format string."""

@staticmethod
def serialize_time(attr, **kwargs) -> str:
    """Serialize time to ISO format string."""

@staticmethod
def serialize_duration(attr, **kwargs) -> str:
    """Serialize timedelta to ISO-8601 duration."""

@staticmethod
def serialize_decimal(attr, **kwargs) -> float:
    """Serialize Decimal to float."""

@staticmethod
def serialize_base64(attr, **kwargs) -> str:
    """Serialize bytes to base64 string."""

@staticmethod
def serialize_bytearray(attr, **kwargs) -> str:
    """Serialize bytearray to base64 string."""

# Static deserialization methods
@staticmethod
def deserialize_iso(attr) -> datetime:
    """Deserialize ISO-8601 string to datetime."""

@staticmethod
def deserialize_rfc(attr) -> datetime:
    """Deserialize RFC-1123 string to datetime."""

@staticmethod
def deserialize_unix(attr) -> datetime:
    """Deserialize Unix timestamp to datetime."""

@staticmethod
def deserialize_date(attr) -> date:
    """Deserialize ISO date string to date object."""

@staticmethod
def deserialize_time(attr) -> time:
    """Deserialize ISO time string to time object."""

@staticmethod
def deserialize_duration(attr) -> timedelta:
    """Deserialize ISO duration to timedelta."""

@staticmethod
def deserialize_decimal(attr) -> Decimal:
    """Deserialize string to Decimal object."""

@staticmethod
def deserialize_base64(attr) -> bytes:
    """Deserialize base64 string to bytes."""

@staticmethod
def deserialize_bytearray(attr) -> bytearray:
    """Deserialize base64 string to bytearray."""

Key Transformers

Functions for transforming object keys during serialization/deserialization.

def attribute_transformer(key: str, attr_desc: dict, value) -> tuple:
    """
    Transform using Python attribute names.
    
    Parameters:
    - key: Attribute name
    - attr_desc: Attribute metadata
    - value: Attribute value
    
    Returns:
    Tuple of (key, value)
    """

def full_restapi_key_transformer(key: str, attr_desc: dict, value) -> tuple:
    """
    Transform using full REST API key path.
    
    Parameters:
    - key: Attribute name
    - attr_desc: Attribute metadata
    - value: Attribute value
    
    Returns:
    Tuple of (key_list, value) for nested structures
    """

def last_restapi_key_transformer(key: str, attr_desc: dict, value) -> tuple:
    """
    Transform using last component of REST API key.
    
    Parameters:
    - key: Attribute name
    - attr_desc: Attribute metadata
    - value: Attribute value
    
    Returns:
    Tuple of (last_key, value)
    """

Validation

Comprehensive validation system with multiple validation rules.

@classmethod
def validate(cls, data, name: str, **kwargs):
    """
    Validate data against specified rules.
    
    Parameters:
    - data: Data to validate
    - name: Field name for error reporting
    - kwargs: Validation rules (required, min_length, max_length, etc.)
    
    Returns:
    Validated data
    
    Raises:
    ValidationError if validation fails
    """

# Validation rules supported in kwargs:
# - required: bool - Field cannot be None
# - min_length: int - Minimum string/array length
# - max_length: int - Maximum string/array length  
# - minimum: int/float - Minimum numeric value
# - maximum: int/float - Maximum numeric value
# - min_items: int - Minimum array items
# - max_items: int - Maximum array items
# - pattern: str - Regex pattern to match
# - unique: bool - Array items must be unique
# - multiple: int/float - Value must be multiple of this

Usage Examples

Basic Serialization

from msrest.serialization import Serializer

# Create serializer
serializer = Serializer()

# Serialize for URL parameter
user_id = 123
url_param = serializer.url('user_id', user_id, 'int')  # "123"

# Serialize for query parameter
tags = ['python', 'rest', 'api']
query_param = serializer.query('tags', tags, '[str]')  # "python,rest,api"

# Serialize for request body
data = {'name': 'John', 'age': 30}
body = serializer.body(data, 'UserModel')

Model Class Usage

from msrest.serialization import Model

class User(Model):
    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'email': {'key': 'email', 'type': 'str'},
        'age': {'key': 'age', 'type': 'int'}
    }
    _validation = {
        'name': {'required': True, 'min_length': 1},
        'email': {'required': True, 'pattern': r'^[^@]+@[^@]+\.[^@]+$'},
        'age': {'minimum': 0, 'maximum': 150}
    }

# Create and validate model
user = User(name='John Doe', email='john@example.com', age=30)
validation_errors = user.validate()

if not validation_errors:
    # Serialize to JSON
    json_data = user.serialize()
    
    # Convert to dictionary
    user_dict = user.as_dict()

Deserialization

from msrest.serialization import Deserializer

# Create deserializer with model classes
classes = {'User': User, 'Address': Address}
deserializer = Deserializer(classes)

# Deserialize JSON response
json_response = '{"name": "John", "email": "john@example.com", "age": 30}'
user = deserializer('User', json_response)

# Deserialize from dictionary
response_dict = {'name': 'Jane', 'email': 'jane@example.com', 'age': 25}
user = User.from_dict(response_dict)

Date/Time Handling

from datetime import datetime, date, timedelta
from msrest.serialization import Serializer

serializer = Serializer()

# Serialize datetime to ISO-8601
dt = datetime(2023, 12, 25, 15, 30, 0)
iso_string = serializer.serialize_iso(dt)  # "2023-12-25T15:30:00Z"

# Serialize date
d = date(2023, 12, 25)
date_string = serializer.serialize_date(d)  # "2023-12-25"

# Serialize duration
delta = timedelta(hours=2, minutes=30)
duration_string = serializer.serialize_duration(delta)  # "PT2H30M"

XML Serialization

from msrest.serialization import Model

class Product(Model):
    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'price': {'key': 'price', 'type': 'float'}
    }
    _xml_map = {
        'name': 'Product',
        'ns': 'http://example.com/products'
    }

product = Product(name='Widget', price=19.99)

# Serialize to XML
xml_data = product.serialize(is_xml=True)

Custom Validation

from msrest.serialization import Model
from msrest.exceptions import ValidationError

class OrderItem(Model):
    _attribute_map = {
        'quantity': {'key': 'quantity', 'type': 'int'},
        'price': {'key': 'price', 'type': 'float'}
    }
    _validation = {
        'quantity': {'required': True, 'minimum': 1, 'maximum': 1000},
        'price': {'required': True, 'minimum': 0.01}
    }

# This will raise ValidationError
try:
    item = OrderItem(quantity=0, price=-5.00)
    item.validate()
except ValidationError as e:
    print(f"Validation failed: {e}")

Exception Handling

from msrest.exceptions import SerializationError, DeserializationError, ValidationError

try:
    # Serialization
    serialized = serializer.body(data, 'ComplexType')
    
    # Deserialization  
    deserialized = deserializer('ComplexType', response_data)
    
except SerializationError as e:
    print(f"Serialization failed: {e}")
except DeserializationError as e:
    print(f"Deserialization failed: {e}")
except ValidationError as e:
    print(f"Validation failed: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-msrest

docs

authentication.md

configuration.md

exceptions.md

index.md

paging.md

pipeline.md

polling.md

serialization.md

service-client.md

tile.json