Use the Python SDK

Updated at:

IoT Platform provides a cloud SDK for Python. Learn how to install and configure the Python SDK and use it to call cloud APIs.

Install the SDK

  1. Install the Python development environment.

    Go to the official Python website to download and install the Python package. The Python SDK supports Python 3.6 and later.

  2. Install pip, the package management tool for Python. (If you already have pip installed, skip this step.)

    Go to the official pip website to download and install the pip package.

  3. Install the IoT Python SDK.

    Run the following command with administrative permission to install the IoT Python SDK. For instructions on how to use the SDK, see the new alibabacloud-python-sdk.

    pip3 install alibabacloud_tea_openapi
    
    # Install the new version of the IoT SDK.
    pip3 install alibabacloud_iot20180120
    # Install a specific SDK version. Version 3.0.9 is used as an example.
    pip3 install alibabacloud_iot20180120==3.0.9 
    
  4. Install the alibabacloud-tea-console package to print logs to the console.

    Run the following command with administrative permission:

    pip3 install alibabacloud-tea-console
  5. Import the IoT Python SDK files into your 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 the SDK

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

  2. Create a client object instance. Use the IotClient(config) method to load the SDK information from config and initialize the SDK client.

The following code provides an example of how to initialize the SDK for the China (Shanghai) region. In your actual scenario, replace the endpoint with the one for the region where your IoT Platform service is located.

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 region ID of your IoT Platform service. This is used to construct the service endpoint in the format: iot.${RegionId}.aliyuncs.com.

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

For more information about how to specify a region ID, see Regions and zones.

For more information about SDK client settings, such as HTTP request configuration, proxy configuration, timeout mechanisms, and retry mechanisms, see Advanced Configurations.

Make a call

The IoT Platform cloud SDK encapsulates each API in a ${API_Name}Request class.

Steps

  1. The SDK client initialization is complete. For more information, see SDK Initialization.

  2. Create an API request object. This creates a request instance of the ${API_Name}Request class.

  3. Use the request object instance and the set_${RequestParameterName} method to set the required request parameter values for the API.

  4. Use the initialized client object to call the ${api_name_with_underscores}(request) method. This method returns the result of the API call. Methods with the _async suffix are asynchronous method calls.

    For example: invoke_things_service(request) and invoke_things_service_async(request).

For more information about IoT Platform cloud APIs, see API list. For descriptions of the request parameters in the request and the response parameters in the response, see the documentation for the specific API.

This topic uses the Pub API as an example to show how to publish a message to a topic. For information about request parameters, see Pub.

Important

In the following code, iotInstanceId is the instance ID. For more information about instances, see Instance overview.

For information about how to purchase an instance, see Purchase an Enterprise instance.

For information about how to obtain an instance ID, see IoT Platform instance-related FAQ.

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 to send. A Base64-encoded string of "hello world".
    message_content='aGVsbG8gd29ybGQ=',
    # The custom topic of the device that will receive the message.
    topic_full_name='/${productKey}/${deviceName}/user/get',
    # The method to send the message. QoS 0 and QoS 1 are supported.
    qos=0
)
response = client.pub(request)
print('response : ' + response)

Complete code example

Note

In your actual scenario, replace the parameter values based on the parameter descriptions provided earlier in this topic.

# -*- coding: utf-8 -*-
import os
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

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> IotClient:
        """
        Initialize the account client with an AccessKey ID and AccessKey secret.
        @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 IotClient(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        """
        Synchronous call method
        """
        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 to send. A Base64-encoded string of "hello world".
                message_content='eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=',
                # The custom topic of the device that will receive the message.
                topic_full_name='/${productKey}/${deviceName}/user/get',
                # The method to send the message. QoS 0 and QoS 1 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 method
        """
        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 to send. A Base64-encoded string of "hello world".
                message_content='eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=',
                # The custom topic of the device that will receive the message.
                topic_full_name='/${productKey}/${deviceName}/user/get',
                # The method to send the message. QoS 0 and QoS 1 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 go to the IoT Platform Cloud SDK Example Center to view or download sample code for API calls. The sample code includes examples for SDKs in languages such as Java, Python, PHP, Node.js, Go, C++, and .NET.

The Alibaba Cloud OpenAPI Developer Portal provides an online API debugging tool. On the API debugging page, you can quickly search for and test API calls. The system automatically generates sample SDK code for different languages based on the parameters that you enter. The sample code is displayed on the SDK Example tab on the right side of the page. On the Call Result tab, you can view the request URL and the response in JSON format.