Python SDK example
You can use the Alibaba Cloud Python SDK to call Data Service APIs and retrieve data. This topic shows how to call the Preset Metric API.
Prerequisites
-
To call a preset metric API, make sure that you have created a product and a device, and backed up the data. For more information, see preset metric API.
-
To call a product data API or a custom service API, make sure that you have created the required API. For more information, see product data API and custom service API.
For more information, see Manage and use APIs.
Install the SDK
-
Install the Python development environment.
Visit the official Python website to download and install the Python installer. The Python SDK supports Python 2.7.x and 3.x.
-
Install pip, the package manager for Python. (Skip this step if pip is already installed.)
Visit the official pip website to download and install the pip package.
-
Run the following commands as an administrator to install the IoT Python SDK.
For information about the latest version, see aliyun-python-sdk-iot.
pip3 install alibabacloud_tea_openapi # Install the latest IoT SDK. pip3 install alibabacloud_iot20180120 # Install a specific SDK version. The following example installs version 3.0.9. pip3 install alibabacloud_iot20180120==3.0.9 -
Import the required IoT Python SDK modules into your Python file.
from alibabacloud_iot20180120.client import Client from alibabacloud_iot20180120.models import ListAnalyticsDataRequest, ListAnalyticsDataRequestCondition from alibabacloud_tea_openapi.models import Config
Make an API call
The following sample code shows how to call a Preset Metric API of Data Service to query historical device count statistics. You can adapt this code to call other APIs by modifying the parameters.
The rate limit for Data Service APIs is 100 requests per second (QPS) per Alibaba Cloud account.
from alibabacloud_iot20180120.client import Client
from alibabacloud_iot20180120.models import ListAnalyticsDataRequest, ListAnalyticsDataRequestCondition
from alibabacloud_tea_openapi.models import Config
config = Config(
access_key_id='yourAccessKeyID',
access_key_secret='yourAccessKeySecret',
region_id='cn-shanghai'
)
client = Client(config)
request = ListAnalyticsDataRequest()
# The path of the API to call.
request.api_path = '/iot-cn-npk1v******/system/query/hist_dev_cnt_stat'
# The ID of your IoT Platform instance.
request.iot_instance_id = 'iot-cn-npk1v******'
# The page number.
request.page_num = 1
# The number of results to return per page.
request.page_size = 100
# Business-related request parameters. For more information about how to configure Condition, see the following description.
conditions = []
condition = ListAnalyticsDataRequestCondition("__instance_id__")
condition.operate = '='
condition.value = 'iot-public'
conditions.append(condition)
condition1 = ListAnalyticsDataRequestCondition("entityId")
condition1.operate = '='
condition1.value = 'all'
conditions.append(condition1)
condition2 = ListAnalyticsDataRequestCondition("statDate")
condition2.operate = '='
condition2.value = '20210221'
conditions.append(condition2)
request.condition = conditions
response = client.list_analytics_data(request)
print(response.body.data)
-
System request parameters
Parameter
Type
Required
Example
Description
access_key_id
String
Yes
LTAI****************
Log in to the IoT Platform console. Hover over your profile picture and click AccessKey Management to obtain your AccessKey ID and AccessKey Secret.
NoteLog in to the IoT Platform console. Hover over your profile picture and click AccessKey Management to obtain your AccessKey ID and AccessKey Secret.
access_key_secret
String
Yes
yourAccessKeySecret
region_id
String
Yes
cn-shanghai
The region ID. For more information, see Supported regions.
api_path
String
Yes
/iot-cn-npk1v******/system/query/hist_dev_cnt_stat
The API path. In the Data Service section, find the API in the API list and click View. The API path is displayed on the details page. For more information, see Manage and use.
page_num
Integer
Required for paginated results.
1
The page number.
page_size
Integer
Required for paginated results.
100
The number of entries to return per page. Maximum: 100.
iot_instance_id
String
Yes
iot-cn-npk1u******
The ID of the IoT Platform instance.
-
Business-related request parameters
Parameter
Type
Required
Description
Related code
ListAnalyticsDataRequestCondition
String
Yes
The request parameter name.
condition = ListAnalyticsDataRequestCondition("__instance_id__")operate
String
Yes
The operator for the request parameter. Valid values:
-
=: Specifies that the parameter must be a specific value. -
BETWEEN: Specifies that the parameter must be within a specific range. -
IN: Specifies that the parameter can be one of multiple values. -
!=: Specifies that the parameter cannot be a specific value.
condition.operate = '='value
String
No
The value of the request parameter.
ImportantRequired unless the operator is
BETWEEN.condition.value = 'iot-public'between_start
String
No
The start of the value range.
ImportantThe start of the value range.
condition.between_start = '0'between_end
String
No
Required if the operator is
BETWEEN.ImportantThe end of the value range.
condition.between_end = '1000'Each request parameter requires a corresponding
conditionobject. View the API details page to see the required parameters and configure aconditionobject for each. For more information about how to view API request parameters, see Manage APIs.In the example code, the API has three request parameters: __instance_id__, entityId, and statDate. They correspond to
condition,condition1, andcondition2respectively. -
Results
-
Success
On the API details page, you can view detailed descriptions of the response parameters. For more information, see Manage and use.
The following example shows a successful response, which contains device count statistics for the public instance on February 21, 2021.
{'HasNext': False, 'ResultJson': '[{"statDate":"20210221","actDevCnt":2942,"onlineDevCntCompare":0.00,"livelyDevCntCompare":8.99,"livelyDevCnt":1527,"onlineDevRate":23.08,"crtDevCnt":169025,"livelyDevRate":51.90,"crtDevCntCompare":0.08,"onlineDevCnt":679,"actDevRate":1.74,"actDevCntCompare":4.55}]', 'PageNum': 1, 'PageSize': 100} -
If a call fails, use the error code in the response to identify the cause. For more information about error codes, see Error codes.
The following example shows a failed response. The parameter
__instance_idd__is invalid. Change it to__instance_id__and retry the call.Traceback (most recent call last): File "xxx/PythonDemo.py", line 44, in <module> response = client.list_analytics_data(request) File "xxx\venv\lib\site-packages\alibabacloud_iot20180120\client.py", line 4883, in list_analytics_data return self.list_analytics_data_with_options(request, runtime) File "xxx\venv\lib\site-packages\alibabacloud_iot20180120\client.py", line 4862, in list_analytics_data_with_options self.do_rpcrequest('ListAnalyticsData', '2018-01-20', 'HTTPS', 'POST', 'AK', 'json', req, runtime) File "xxx\venv\lib\site-packages\alibabacloud_tea_openapi\client.py", line 239, in do_rpcrequest raise UnretryableException(_last_request, _last_exception) Tea.exceptions.UnretryableException: Error: InvalidParameter Parameter code: 400, invalid parameter:redundant query param : __instance_id__ request id: EB927523-B5FA-4393-A3F5-7E7Ixxx Response: {'RequestId': 'EB927523-B5FA-4393-A3F5-xxx'}