Registry / azure / msrest

msrest

JSON →
library0.7.1pypypi✓ verified 49d ago

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.

azurehttp-networkingserialization
pip install msrest
Install & Compatibility
Where this runs
tested against v0.7.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.925 runs
installs and imports cleanly · install 0.0s · import 1.176s · 25.5MB
glibc
py 3.103.925 runs
installs and imports cleanly · install 2.7s · import 0.951s · 26MB
24MB installed
● package 24MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ServiceClient
from msrest import ServiceClient
Core client for making REST calls.
Serializer
from msrest.serialization import Serializer
Used to convert Python objects to API-compatible formats.
Deserializer
from msrest.serialization import Deserializer
Used to convert API responses into Python objects.
HttpOperationError
from msrest.exceptions import HttpOperationError
Common exception for HTTP operation failures.
SerializationError
from azure.core.exceptions import SerializationError
from msrest.exceptions import SerializationError
Moved to `azure.core.exceptions` in msrest 0.7.0.
DeserializationError
from azure.core.exceptions import DeserializationError
from msrest.exceptions import DeserializationError
Moved to `azure.core.exceptions` in msrest 0.7.0.

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)}")
Debug
Known issues
deprecatedThe `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.
affects: >=0.7.1
breakingIn `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 ...`.
affects: >=0.7.0
gotchaDateTime 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.
affects: <0.7.0 (bug fixes in 0.6.20/0.6.21 for certain datetime types), all versions (general handling)
gotchaMixing 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.
affects: All versions, especially when used in complex dependency trees
breakingmsrest.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.
affects: all versions
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.
affects: All versions, particularly when used in newer Python environments (e.g., Python 3.13) or with improperly registered models.
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'msrest'
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.
ModuleNotFoundError: No module named 'msrestazure'
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`.
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')
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.
AttributeError: 'BasicTokenAuthentication' object has no attribute 'get_token'
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.
Upgrade
Version history
0.7.1latest on PyPI
Audit
Dependencies
requestsrequiredUsed internally for HTTP requests.
isodaterequiredRequired for ISO 8601 date/time parsing and formatting during serialization/deserialization.
azure-corerequiredRequired since 0.7.0; common HTTP pipeline components and exception types (e.g., SerializationError, DeserializationError) were moved here.
Agent activity
9 hits · last 30 days
seranking-bot
4
node
2
ahrefsbot
2
Resources