All Products
Search
Document Center

IoT Platform:Examples of using the SDK for Node.js

Last Updated:Oct 16, 2024

Leverage the Node.js SDK from Alibaba Cloud to easily invoke API operations within DataService Studio and retrieve specific data. This topic illustrates how to use the Node.js SDK to call the API for preset metrics, providing both the method and an example.

Prerequisites

  • To call the API for preset metrics, ensure that the product and device are created and that data backup is complete. For detailed instructions, see API for preset metrics.

  • To invoke the product data API or customize a service API, confirm that the corresponding API is established. For detailed instructions, see Product data API and Customize service API.

For more information, see the referenced document.

Install the SDK

  1. To set up the Node.js development environment, visit the official Node.js website and follow the provided installation instructions.

  2. To install the Alibaba Cloud OpenAPI SDK, execute the commands below.

    npm install @alicloud/openapi-client
    npm install @alicloud/iot20180120

Initiate a request

Below is an example of how to call the historical device count statistics from the preset metrics API in DataService Studio. Modify the code as needed based on the parameter descriptions to call the desired API.

Important

Note that the maximum number of requests per second (QPS) for a single Alibaba Cloud account when calling the DataService Studio API is 100.

const Config = require('@alicloud/openapi-client').Config;
const ListAnalyticsDataRequest = require('@alicloud/iot20180120').ListAnalyticsDataRequest;
const IotClient = require('@alicloud/iot20180120');
const ListAnalyticsDataRequestCondition = require('@alicloud/iot20180120/dist/client').ListAnalyticsDataRequestCondition;
// Create a client
const config = new Config();
config.endpoint = "iot.cn-shanghai.aliyuncs.com";
config.accessKeyId = "LTAI4FyDFmKN************";
config.accessKeySecret = "WF3onkl8cq3cTyVW8n************";
config.regionId = "cn-shanghai";
async function main() {
    const client = new IotClient.default(config);
    // Create a request object
    const listAnalyticsDataRequest = new ListAnalyticsDataRequest();
    // Your API Path
    listAnalyticsDataRequest.apiPath = '/iot-cn-npk1v******/system/query/hist_dev_cnt_stat'
    // Paging parameter: page number
    listAnalyticsDataRequest.pageNum = 1;
    // Paging parameter: page size
    listAnalyticsDataRequest.pageSize = 100;
    // The instance ID where your API is located
    listAnalyticsDataRequest.iotInstanceId = 'iot-cn-npk1v******' 
    // Your API business-related request parameters. For the configuration description of Condition, see the relevant description below.
    const conditions = [];
    const condition = new ListAnalyticsDataRequestCondition();
    condition.operate = '=';
    condition.fieldName = '__instance_id__';
    condition.value = 'iot-public'
    conditions.push(condition)
    const condition1 = new ListAnalyticsDataRequestCondition();
    condition1.operate = '=';
    condition1.fieldName = 'entityId';
    condition1.value = 'all'
    conditions.push(condition1)
    const condition2 = new ListAnalyticsDataRequestCondition();
    condition2.operate = '=';
    condition2.fieldName = 'statDate';
    condition2.value = '20210221'
    conditions.push(condition2)
    listAnalyticsDataRequest.condition = conditions;
    try {
        const response = await client.listAnalyticsData(listAnalyticsDataRequest)
        console.log(response)
    } catch (ex) {
        console.log(ex);
    }
}
main();
  • System request parameters:

    Name

    Type

    Required

    Example value

    Description

    endpoint

    String

    Yes

    iot.cn-shanghai.aliyuncs.com

    The endpoint for the Alibaba Cloud service API server. Ensure the region matches the IoT Platform product's region.

    In this example, the region is East China 2 (cn-shanghai).

    accessKeyId

    String

    Yes

    LTAI4FyDFmKN************

    Navigate to the IoT Platform console, hover over the account profile picture, and click AccessKey Management to retrieve the AccessKey ID and AccessKey Secret.

    Note

    Resource Access Management (RAM) users must have the AliyunIOTFullAccess policy attached to manage IoT Platform resources. If not, the connection will fail. For authorization details, see Grant RAM user access to IoT Platform.

    accessKeySecret

    String

    Yes

    WF3onkl8cq3cTyVW8n************

    regionId

    String

    Yes

    cn-shanghai

    The region code. For a list of supported regions, see Supported regions.

    apiPath

    String

    Yes

    iot-cn-npk1u******

    The API operation path. View the API list in DataService Studio and click View to access the API's product page for the API Patch value. For more details, see the referenced document.

    pageNum

    Integer

    Required when paging is enabled

    1

    The page number for pagination.

    pageSize

    Integer

    Required when paging is enabled

    100

    The number of entries per page, up to a maximum of 100.

    iotInstanceId

    String

    Yes

    iot-cn-npk1v******

    The instance ID where your API is deployed.

  • Business-related request parameters:

    Name

    Type

    Required

    Description

    Related code

    fieldName

    String

    Yes

    The name of the field for the request parameter.

     condition.fieldName = '__instance_id__';

    operate

    String

    Yes

    The operator used for the request parameter. Options include:

    • = for exact matches.

    • BETWEEN for ranges.

    • IN for multiple values.

    • != for exclusions.

     condition.operate = '=';

    value

    String

    No

    The specific value for the request parameter.

    Important

    This parameter is mandatory unless the operator is BETWEEN.

     condition.value = 'iot-public';

    betweenStart

    String

    No

    The starting value for a range parameter.

    Important

    Required when the operator is BETWEEN.

     condition.betweenStart = '0';

    betweenEnd

    String

    No

    The ending value for a range parameter.

    Important

    Required when the operator is BETWEEN.

     condition.betweenEnd = '1000';

    Each request parameter is associated with a condition. You can set a specific number of conditions on the API's product page. For details on viewing API request parameters, see Manage API.

    In the provided example code, the API has three request parameters: __instance_id__, entityId, and statDate, which correspond to condition, condition1, and condition2 respectively.

Execution result

  • Success:

    Detailed descriptions of the returned parameters can be found on the corresponding API's product page. For specific operations, see the referenced document.

    The example below demonstrates a successful API call, returning device count statistics for the public instance from February 21, 2021, to the time of the API call.

    ListAnalyticsDataResponse {
      headers: {
        date: 'Mon, 15 Mar 2021 10:40:58 GMT',
        'content-type': 'application/json;charset=utf-8',
        'content-length': '425',
        connection: 'keep-alive',
        'access-control-allow-origin': '*',
        'access-control-allow-methods': 'POST, GET, OPTIONS',
        'access-control-allow-headers': 'X-Requested-With, X-Sequence, _aop_secret, _aop_signature',
        'access-control-max-age': '172800',
        'x-acs-request-id': 'F278FA13-11E6-42BC-9883-3566AC******'
      },
      body: ListAnalyticsDataResponseBody {
        requestId: 'F278FA13-11E6-42BC-9883-3566AC******',
        success: true,
        data: ListAnalyticsDataResponseBodyData {
          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
        }
      }
    }
  • Failure:

    Understanding the reason for a failed call is possible by examining the error code in the result.

    The example below shows a failed API call due to an invalid request parameter, __instance_idd__. Correct it to __instance_id__ and attempt the call again.