All Products
Search
Document Center

IoT Platform:Use IoT Platform SDK for Python

Last Updated:Sep 09, 2024

IoT Platform provides an SDK for Python. This topic describes how to install and configure IoT Platform SDK for Python. This topic also provides sample code on how to use the SDK to call API operations of IoT Platform.

Install IoT Platform SDK for Python

  1. Install a Python development environment.

    Download a Python installation package from the official Python website and install Python. The SDK for Python requires Python 3.6 or later.

  2. Install pip to manage Python packages. If you have installed pip, skip this step.

    Download a pip installation package from the official pip website and install pip.

  3. Install IoT Platform SDK for Python.

    Run the following commands as an administrator to install IoT Platform SDK for Python. For more information about how to use the SDK, see alibabacloud-python-sdk.

    pip3 install alibabacloud_tea_openapi
    
    # Install the latest version of IoT Platform SDK for Python. 
    pip3 install alibabacloud_iot20180120
    # Install a specific version of IoT Platform SDK for Python. In this example, IoT Platform SDK for Python version 3.0.9 is installed. 
    pip3 install alibabacloud_iot20180120==3.0.9 
    
  4. Install the alibabacloud-tea-console package to display logs in the IoT Platform console.

    Run the following command as an administrator:

    pip3 install alibabacloud-tea-console
  5. Import the files that are related to IoT Platform SDK for Python to a Python file.

    from Tea.core import TeaCore
    from alibabacloud_iot20180120.client import Client as IotClient
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_iot20180120 import models as iot_models
    from alibabacloud_tea_console.client import Client as ConsoleClient
    from alibabacloud_tea_util.client import Client as UtilClient
    ...

Initialize IoT Platform SDK for Python

  1. Create the config object to store SDK initialization information, such as the AccessKey ID, AccessKey secret, and region ID.

  2. Create the client instance and call the IotClient(config) method to load the SDK information from the config object. Then, the SDK is initialized.

For example, if you want to use the SDK in the China (Shanghai) region, you can use the following code to initialize the SDK. In the production environment, you must select the region where IoT Platform is activated.

config = open_api_models.Config()
# Your AccessKey ID.
config.access_key_id = os.environ.get('ALICLOUD_ACCESS_KEY_ID')
# Your AccessKey secret.
config.access_key_secret = os.environ.get('ALICLOUD_ACCESS_KEY_SECRET')
# Your region ID.
config.region_id = 'cn-shanghai'
client = IotClient(config)

Parameter

Description

region_id

The ID of the region where your IoT Platform instance resides. The region ID is used in the endpoint for service access. The endpoint is in the iot.${RegionId}.aliyuncs.com format.

You can view the region in the upper-left corner of the IoT Platform console.

For more information about the formats of region IDs, see Supported regions.

Initiate a request

The SDK encapsulates a class for each API operation. The class name is in the ${API name}+"Request" format. You can use the class to initiate API requests.

Procedure

  1. Initialize the SDK. For more information, see Initialize the SDK.

  2. Create an API request by generating a request instance whose class name is in the ${API name}+"Request" format.

  3. Call the "set"+${Request parameter} method of the request instance to specify the request parameters.

  4. Call the ${API name with words connected by underscores}(request) method of the client instance to obtain the response. A method whose name ends with _async indicates an asynchronous method.

    Examples: invoke_things_service(request) and invoke_things_service_async(request).

For more information about the API operations of IoT Platform, see List of operations by function. For more information about the request parameters and response parameters of each API operation, see the API reference.

The following example shows how to call the Pub operation to publish a message to a topic. For more information about request parameters, see Pub.

Important

In the following sample code, ${iotInstanceId} specifies the ID of an instance. You can view the ID of the instance on the Overview page in the IoT Platform console.

  • If your instance has an ID, you must specify the ID for this parameter. Otherwise, the call fails.

  • If no Overview page or ID is generated for your instance, you do not need to configure this parameter. You must delete the request code that is related to the IotInstanceId parameter or specify an empty string ("") for the parameter. Otherwise, the call fails.

For more information about IoT Platform instances, see Overview. For more information about how to purchase an instance, see Purchase Enterprise Edition instances. For more information, see FAQ about IoT Platform instances.

request = iot_models.PubRequest(
    # The ID of the IoT Platform instance. 
    iot_instance_id='${iotInstanceId}',
    # The ProductKey of the product. 
    product_key='${productKey}',
    # The message body that you want to send. Encode "hello world" in Base64 as a string. 
    message_content='aGVsbG8gd29ybGQ=',
    # The name of the custom topic that is used by a device to receive the message. 
    topic_full_name='/${productKey}/${deviceName}/user/get',
    # The quality of service (QoS) level of the message. QoS 0 and QoS 1 messages are supported. 
    qos=0
)
response = client.pub(request)
print('response : ' + response)

Complete sample code

Note

You can replace the values of the preceding parameters with actual values based on your business scenario.

# -*- coding: utf-8 -*-
import sys
from typing import List
from Tea.core import TeaCore
from alibabacloud_iot20180120.client import Client as IotClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_iot20180120 import models as iot_models
from alibabacloud_tea_console.client import Client as ConsoleClient
from alibabacloud_tea_util.client import Client as UtilClient

access_key_id = os.environ.get('ACCESS_KEY_ID')
access_key_secret = os.environ.get('ACCESS_KEY_SECRET')

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> IotClient:
        """
        Use your AccessKey ID and AccessKey secret to initialize the client.
        """
        Use your AccessKey ID and AccessKey secret to initialize the client.
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config()
        # Your AccessKey ID.
        config.access_key_id = os.environ.get('ALICLOUD_ACCESS_KEY_ID')
        # Your AccessKey secret.
        config.access_key_secret = os.environ.get('ALICLOUD_ACCESS_KEY_SECRET')
        # Your region ID.
        config.region_id = 'cn-shanghai'
        return Iot20180120Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        """
        Synchronous call
        """
        try:
            client = Sample.create_client('${accessKey}', '${accessKeySecret}')
            request = iot_models.PubRequest(
                # The ID of the IoT Platform instance. 
                iot_instance_id='${iotInstanceId}',
                # The ProductKey of the product. 
                product_key='${productKey}',
                # The message body that you want to send. Encode "hello world" in Base64 as a string. 
                message_content='eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=',
                # The custom topic that is used to publish the message. 
                topic_full_name='/${productKey}/${deviceName}/user/get',
                # The QoS level of the message. QoS 0 and QoS 1 messages are supported. 
                qos=0
            )
            response = client.pub(request)
            ConsoleClient.log(UtilClient.to_jsonstring(TeaCore.to_map(response)))
        except Exception as error:
            ConsoleClient.log(error.message)

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        """
        Asynchronous call
        """
        try:
            client = Sample.create_client('${accessKey}', '${accessKeySecret}')
            request = iot_models.PubRequest(
                # The ID of the IoT Platform instance. 
                iot_instance_id='${iotInstanceId}',
                # The ProductKey of the product. 
                product_key='${productKey}',
                # The message body that you want to send. Encode "hello world" in Base64 as a string. 
                message_content='eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=',
                # The custom topic that is used to publish the message. 
                topic_full_name='/${productKey}/${deviceName}/user/get',
                # The QoS level of the message. QoS 0 and QoS 1 messages are supported. 
                qos=0
            )
            response = await client.pub_async(request)
            ConsoleClient.log(UtilClient.to_jsonstring(TeaCore.to_map(response)))
        except Exception as error:
            ConsoleClient.log(error.message)


if __name__ == '__main__':
    Sample.main(sys.argv[1:])

Appendix: Sample code

You can view or download the sample code of API operations in IoT Platform SDK Sample Center. Sample code of SDKs for Java, Python, PHP, Node.js, Go, C++, and .NET is provided.

Alibaba Cloud OpenAPI Explorer provides online debugging tools for API operations. On the API Debugging page, you can search for API operations, call API operations, and generate sample code for API operations of different SDKs. On the right side of the page, you can view the sample code of an SDK on the Sample Code tab. On the Debugging Result tab, you can view the actual request URL and response in the JSON format.