msrest
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.
Common errors
-
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.fixInstall '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. -
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.fixInstall 'msrestazure' using pip: `pip install msrestazure`. -
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.fixInspect 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. -
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`.fixReplace `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.
Warnings
- 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.
- breaking In `msrest` version 0.7.0, `SerializationError` and `DeserializationError` classes were moved from `msrest.exceptions` to `azure.core.exceptions`.
- 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.
- 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.
- 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.
- 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.
Install
-
pip install msrest
Imports
- ServiceClient
from msrest import ServiceClient
- Serializer
from msrest.serialization import Serializer
- Deserializer
from msrest.serialization import Deserializer
- HttpOperationError
from msrest.exceptions import HttpOperationError
- SerializationError
from msrest.exceptions import SerializationError
from azure.core.exceptions import SerializationError
- DeserializationError
from msrest.exceptions import DeserializationError
from azure.core.exceptions import DeserializationError
Quickstart
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)}")