{"id":6534,"library":"azure-iot-hub","title":"Azure IoT Hub Service Library","description":"The `azure-iot-hub` library is part of the Microsoft Azure SDK for Python, providing capabilities to manage IoT Hub resources and interact with connected devices from a backend service. This includes managing device identities, sending cloud-to-device messages, and invoking direct methods on devices. The current version is 2.7.0, and Azure SDKs typically follow a frequent release cadence, with minor updates and bug fixes released regularly.","status":"active","version":"2.7.0","language":"en","source_language":"en","source_url":"https://github.com/Azure/azure-iot-hub-python/","tags":["azure","iot","cloud","sdk","microsoft","iothub"],"install":[{"cmd":"pip install azure-iot-hub","lang":"bash","label":"Install `azure-iot-hub`"}],"dependencies":[],"imports":[{"symbol":"IoTHubRegistryManager","correct":"from azure.iot.hub import IoTHubRegistryManager"},{"symbol":"IoTHubDeviceManager","correct":"from azure.iot.hub import IoTHubDeviceManager"},{"note":"Top-level symbols are generally exposed directly under `azure.iot.hub` for convenience, avoiding deeper imports into `models`.","wrong":"from azure.iot.hub.models import CloudToDeviceMethod","symbol":"CloudToDeviceMethod","correct":"from azure.iot.hub import CloudToDeviceMethod"}],"quickstart":{"code":"import os\nfrom azure.iot.hub import IoTHubRegistryManager\n\n# Retrieve IoT Hub connection string from environment variables for security\nIOT_HUB_CONNECTION_STRING = os.environ.get(\"AZURE_IOT_HUB_CONNECTION_STRING\", \"\")\n\nif not IOT_HUB_CONNECTION_STRING:\n    raise ValueError(\"AZURE_IOT_HUB_CONNECTION_STRING environment variable not set.\")\n\nDEVICE_ID = \"myPythonManagedDevice\"\n\nmanager = None\n\ntry:\n    # Create an instance of the IoTHubRegistryManager\n    # This connection string should be for a service/iothubowner policy\n    manager = IoTHubRegistryManager.from_connection_string(IOT_HUB_CONNECTION_STRING)\n\n    print(f\"Attempting to create device: {DEVICE_ID}\")\n    # Create a new device identity\n    # If the device already exists, this will raise an IoTHubError (409 Conflict)\n    try:\n        device = manager.create_device(DEVICE_ID)\n        print(f\"Device '{device.device_id}' created successfully.\")\n    except Exception as e:\n        if \"409001 DeviceAlreadyExists\" in str(e):\n            print(f\"Device '{DEVICE_ID}' already exists. Retrieving it.\")\n            device = manager.get_device(DEVICE_ID)\n            print(f\"Retrieved device '{device.device_id}'.\")\n        else:\n            raise e\n\n    # You can inspect the device object, e.g., its primary key\n    if device.authentication and device.authentication.symmetric_key:\n        print(f\"Primary key: {device.authentication.symmetric_key.primary_key}\")\n\n    print(\"Successfully interacted with IoT Hub Registry.\")\n\nfinally:\n    # Close the manager to release resources\n    if manager:\n        print(\"Closing IoTHubRegistryManager...\")\n        manager.close()\n        print(\"Manager closed.\")\n","lang":"python","description":"This quickstart demonstrates how to initialize the `IoTHubRegistryManager` using an IoT Hub connection string (preferably from an environment variable for security) and then create or retrieve a device identity within the IoT Hub. It also highlights the importance of closing the manager instance."},"warnings":[{"fix":"Rewrite code following the V2 `azure-iot-hub` SDK patterns. Refer to the official Azure SDK documentation and migration guides for updated import paths and API usage.","message":"Migration from older V1 Python clients like `azure-iothub-service-client` to the V2 SDK `azure-iot-hub` involves significant breaking changes. The package name, module structure (e.g., `azure.iot.hub` vs `azure.iothub`), class names, and API signatures are completely different. Code written for V1 clients will not work with `azure-iot-hub` without extensive modifications.","severity":"breaking","affected_versions":"< 2.0.0 (old clients) vs >= 2.0.0 (azure-iot-hub)"},{"fix":"Ensure you are using the correct library for your specific use case. `azure-iot-hub` for service interactions, `azure-iot-device` for device interactions, and `azure-iot-provisioningservice` for DPS management.","message":"It's crucial to distinguish between `azure-iot-hub`, `azure-iot-device`, and `azure-iot-provisioningservice`. `azure-iot-hub` is for backend *service-side* operations (managing devices, sending C2D messages). `azure-iot-device` is for *device-side* operations (sending D2C messages, receiving C2D messages). `azure-iot-provisioningservice` is for interacting with the Device Provisioning Service. Using the wrong library for a task is a common mistake.","severity":"gotcha","affected_versions":"All versions"},{"fix":"When generating the connection string from the Azure portal, select 'Shared access policies' under 'Security settings' and copy the connection string for a policy like 'iothubowner' or 'service'.","message":"The `IoTHubRegistryManager.from_connection_string` method requires an IoT Hub *service* connection string (e.g., from an `iothubowner` or `service` policy), not a device connection string. Using a device connection string will result in authentication errors.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always ensure `manager.close()` is called when the manager is no longer needed. The recommended pattern is to use a `try...finally` block to guarantee closure, as shown in the quickstart example.","message":"The `IoTHubRegistryManager` instance holds network connections. Failing to call `manager.close()` when you are finished with it can lead to resource leaks and prevent your application from cleanly exiting, especially in long-running processes or serverless functions.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-15T00:00:00.000Z","next_check":"2026-07-14T00:00:00.000Z","problems":[{"fix":"Ensure you have the correct library installed for your use case: for service-side operations, install `pip install azure-iot-hub`. For device-side operations, install `pip install azure-iot-device`. Also, check that none of your Python files are named `azure.py`, `azure.iot.py`, or similar, which can cause import conflicts.","cause":"This error typically occurs because the `azure-iot-hub` package is not installed, the `azure-iot-device` package is installed but the user is trying to import service-side functionalities from it, or a user-created file is named `azure.py`, shadowing the actual `azure` package.","error":"ModuleNotFoundError: No module named 'azure.iot.hub' (or 'azure.iot')"},{"fix":"Verify the connection string format against Azure IoT Hub documentation. Ensure all necessary components (HostName, DeviceId/SharedAccessKeyName, SharedAccessKey) are present and correctly formatted. If using X.509, do not include symmetric key components in the connection string.","cause":"The connection string provided to the client is malformed, contains incorrect key-value pairs, is incomplete, or attempts to mix authentication schemes (e.g., providing a symmetric key string while also specifying X.509 authentication).","error":"ValueError: Invalid Connection String - Invalid Key (or - Incomplete / Unable to parse)"},{"fix":"Check the validity and expiration of your SAS token, device keys, or X.509 certificates. Ensure the device or module is enabled in IoT Hub. For service-side operations, verify that the shared access policy used has the correct permissions (e.g., Registry Write, Service Connect). If using an SDK, it usually handles token renewal; if not, ensure your token generation and renewal logic is correct.","cause":"This indicates an authentication failure. Common causes include an expired Shared Access Signature (SAS) token, incorrect device or module credentials (e.g., primary/secondary keys, X.509 certificates), or the authorization policy used does not have the necessary permissions for the requested operation.","error":"401003 IoTHubUnauthorized / Connection Refused: not authorised"},{"fix":"Investigate network connectivity between the device and Azure IoT Hub. Ensure port 8883 (for MQTT) or 443 (for MQTT over WebSockets) is open if applicable. Check Azure Service Health for IoT Hub regional issues. For persistent issues, review device logs for patterns that might indicate a problem with the device's application logic or resource constraints.","cause":"This error typically occurs when the device's connection to IoT Hub is lost unexpectedly due to network instability, a transient service issue, or during SAS token renewal by the SDK. While the SDK attempts to reconnect, persistent network problems can lead to repeated disconnections.","error":"azure.iot.device.common.transport_exceptions.ConnectionDroppedError: Unexpected disconnection"}]}