msrest

raw JSON →
0.7.1 verified Tue May 12 auth: no python install: verified quickstart: stale deprecated

msrest is the Python client runtime library for AutoRest-generated Python SDKs, primarily used within the Azure SDK ecosystem. It provides functionalities for serialization, deserialization, and HTTP communication, enabling Python clients to interact with REST APIs defined by Swagger/OpenAPI specifications. The current version is 0.7.1, with the latest release being June 2022. The library is now deprecated and will not receive further updates, with its functionalities moved to `azure-identity` and `azure-core`, or vendored directly into SDKs.

pip install msrest
error ModuleNotFoundError: No module named 'msrest'
cause This error occurs when the 'msrest' package is not installed in the Python environment, or when a dependent package (like older Azure SDKs or Ansible collections) fails to correctly install it as a dependency.
fix
Install 'msrest' using pip: pip install msrest or pip install 'azure-mgmt-resourcegraph' (or the specific Azure SDK package requiring it) to ensure all dependencies are met.
error ModuleNotFoundError: No module named 'msrestazure'
cause This error indicates that the 'msrestazure' package, often used for Azure-specific authentication and resource management functionalities with AutoRest-generated clients, is missing from the Python environment.
fix
Install 'msrestazure' using pip: pip install msrestazure.
error msrest.exceptions.DeserializationError: Unable to deserialize to object: type, KeyError: 'key: int; value: str' OR AttributeError: 'str' object has no attribute 'get' (or '_attribute_map')
cause These errors typically occur during deserialization when the actual data received from a REST API does not match the expected data model or schema defined for the Python client. This can be due to API changes, incorrect data types, or malformed JSON/XML responses.
fix
Inspect the raw HTTP response content to understand its structure. Compare it against the expected model definition in the SDK. If the API has changed, update the SDK version or adjust your code to handle the new response format. If the issue persists, manually deserialize the problematic part or consider using azure-core's updated serialization.
error AttributeError: 'BasicTokenAuthentication' object has no attribute 'get_token'
cause This error arises when code expects an authentication object to have a `get_token` method (common in newer Azure SDKs that use `azure-identity`), but is instead provided with an older `msrest.authentication.BasicTokenAuthentication` object, which lacks this method. This is a common symptom during migration from older `msrest`-based authentication to `azure-identity`.
fix
Replace msrest.authentication.BasicTokenAuthentication with credentials from the azure-identity library, such as DefaultAzureCredential or ManagedIdentityCredential, which provide the get_token method. Wrap the azure-identity credential if the client still explicitly expects a msrest.authentication object using a compatibility wrapper.
deprecated The `msrest` library is officially deprecated and no longer receives updates. Its functionalities have been moved to `azure-identity` for authentication and `azure-core` or are vendored directly into newer Azure SDKs. It will soon be archived.
fix For new projects or migrations, prefer using `azure-identity` for authentication and `azure-core` for common client infrastructure. For serialization, rely on the specific SDK's vendored logic or custom serializers where `msrest` is not a direct dependency.
breaking In `msrest` version 0.7.0, `SerializationError` and `DeserializationError` classes were moved from `msrest.exceptions` to `azure.core.exceptions`.
fix Update import statements for these exceptions from `from msrest.exceptions import ...` to `from azure.core.exceptions import ...`.
gotcha DateTime objects, especially timezone-naive ones, can cause serialization or deserialization issues. `msrest` expects RFC1123 or ISO 8601 formatted strings and prefers timezone-aware datetime objects for serialization.
fix Always use timezone-aware `datetime` objects (e.g., `datetime.datetime.now(datetime.timezone.utc)`). Ensure incoming datetime strings from APIs are in a standard format (ISO 8601 is preferred). If custom formats are necessary, manual pre-processing might be needed.
gotcha Mixing different versions of Azure SDKs that have varying `msrest` dependencies can lead to `pip` dependency resolution conflicts. Some newer SDKs have removed `msrest` as a direct dependency or require specific versions.
fix Consolidate SDK versions where possible. If conflicts arise, consider upgrading to SDK versions that explicitly remove `msrest` as a dependency or align `msrest` versions across your project. In some cases, using `pip install --no-deps` for `msrest` and managing its core dependencies might be a workaround, but is not recommended.
breaking msrest.serialization.body can raise `TypeError: issubclass() arg 1 must be a class` if the `data_type` argument is not a valid class object or a string name that the serializer can resolve to a class via its known models. This often happens if the serializer's `_models` dictionary is not correctly populated or if an unresolvable string is passed. Additionally, it might encounter `KeyError: 'is_xml'` if an internal XML serialization path is triggered without the necessary `is_xml` keyword argument.
fix When calling `serializer.body(data, data_type)`, ensure that `data_type` is either the actual Python class object (e.g., `MyModel`) or a string representation (e.g., `'MyModel'`) only if the `msrest.serialization.Deserializer` or `Serializer` instance has been explicitly initialized with a `_models` dictionary that maps the string name to the corresponding class (e.g., `serializer = Deserializer(models={'MyModel': MyModel})`). If the intent is to serialize XML, ensure `is_xml=True` is passed as a keyword argument.
breaking `msrest.serialization.Serializer.body` can fail with `TypeError: issubclass() arg 1 must be a class` when the `data_type` argument (if a string) does not correctly resolve to a registered model class. This indicates an issue with how models are defined or added to the serializer's `_models` collection, or a potential incompatibility/edge case in `msrest`'s internal type resolution logic, especially with newer Python versions (e.g., Python 3.13) where `msrest` is no longer actively maintained.
fix Ensure that any string `data_type` passed to `serializer.body` (or similar methods) corresponds to a class that has been correctly registered with the `msrest.serialization.Serializer` instance. If `data_type` is intended to be a Python class directly, pass the class object itself, not its name as a string. As `msrest` is deprecated, for new projects or migrations, prefer using `azure-identity` for authentication and `azure-core` for common client infrastructure, relying on specific SDK's vendored logic for serialization.
python os / libc status wheel install import disk
3.10 alpine (musl) - - 1.38s 25.5M
3.10 slim (glibc) - - 0.83s 26M
3.11 alpine (musl) - - 1.80s 28.0M
3.11 slim (glibc) - - 1.02s 29M
3.12 alpine (musl) - - 1.49s 19.7M
3.12 slim (glibc) - - 1.02s 20M
3.13 alpine (musl) - - 1.21s 19.3M
3.13 slim (glibc) - - 1.40s 20M
3.9 alpine (musl) - - 1.24s 24.7M
3.9 slim (glibc) - - 1.05s 25M

This example demonstrates how to use `msrest.serialization.Serializer` and `msrest.serialization.Deserializer` to convert Python objects to and from JSON structures based on a defined model schema. It shows how to initialize these components, serialize an object with a datetime field, and then deserialize a mock API response back into a Python object.

import json
import datetime
import isodate # Needed for deserialized datetime object type checking
from msrest.serialization import Serializer, Deserializer

# Define a simple model schema for demonstration
models = {
    'MyModel': {
        'type': 'object',
        'properties': {
            'id': {'type': 'integer', 'format': 'int32'},
            'name': {'type': 'string'},
            'created_at': {'type': 'string', 'format': 'date-time'}
        },
        'required': ['id', 'name']
    }
}

# Initialize Serializer and Deserializer with defined models
serializer = Serializer(models)
deserializer = Deserializer(models)

# Create a Python object to be serialized
class MyModel:
    def __init__(self, id, name, created_at=None):
        self.id = id
        self.name = name
        self.created_at = created_at

instance_to_serialize = MyModel(
    id=1,
    name='Example Item',
    created_at=datetime.datetime.now(datetime.timezone.utc)
)

# Serialize the object to a format suitable for a REST API call
# The 'MyModel' string refers to the schema key defined in 'models'
serialized_data = serializer.body(instance_to_serialize, 'MyModel')
print("Serialized data:", json.dumps(serialized_data, indent=2))

# Simulate a raw JSON response from a REST API
raw_json_response = {
    "id": 2,
    "name": "Another Example",
    "created_at": "2023-10-27T10:30:00Z"
}

# Deserialize the raw JSON response into a Python object
deserialized_instance = deserializer(MyModel, raw_json_response)
print(f"\nDeserialized name: {deserialized_instance.name}")
print(f"Deserialized created_at: {deserialized_instance.created_at}")
print(f"Type of deserialized created_at: {type(deserialized_instance.created_at)}")