Node.js SDK call example

Updated at:

Use the Alibaba Cloud Node.js SDK to call Data Service APIs and retrieve data. This topic uses a pre-defined metric API to demonstrate how to make an API call.

Prerequisites

  • Before calling a pre-defined metric API, create a product, create a device, and complete the data backup. For more information, see pre-defined metric API.

  • Before calling a product data API or custom service API, create the corresponding API. For more information, see product data API and custom service API.

For more information, see Manage and use APIs.

Install the SDK

  1. Install the Node.js development environment from the official Node.js website.

  2. Run the following commands to install the Alibaba Cloud OpenAPI SDK.

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

Make an API call

This example shows how to call a pre-defined metric API in Data Service to query historical device count statistics. You can modify the code based on the parameter descriptions to call your desired API.

Important

Data Service APIs support up to 100 queries per second (QPS) per Alibaba Cloud account.

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 = "LTAI****************************";
config.accessKeySecret = "yourAccessKeySecret";
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'
    // Pagination parameter: page number.
    listAnalyticsDataRequest.pageNum = 1;
    // Pagination parameter: page size.
    listAnalyticsDataRequest.pageSize = 100;
    // The instance ID for your API.
    listAnalyticsDataRequest.iotInstanceId = 'iot-cn-npk1v******' 
    // The API-specific request parameters. For information about how to configure Condition, see the description later in this topic.
    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:

    Parameter

    Type

    Required

    Example

    Description

    endpoint

    String

    Yes

    iot.cn-shanghai.aliyuncs.com

    The API endpoint of the Alibaba Cloud service. The region must match the region of your IoT Platform product.

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

    accessKeyId

    String

    Yes

    LTAI****************

    To obtain your AccessKey ID and AccessKey Secret, log in to the IoT Platform console, hover over your profile picture, and click AccessKey Management.

    Note

    If you use a RAM user, you must grant the RAM user permissions to manage IoT Platform (AliyunIOTFullAccess). Otherwise, the connection fails. For more information about how to grant permissions, see Grant RAM users the permissions to access IoT Platform.

    accessKeySecret

    String

    Yes

    yourAccessKeySecret

    regionId

    String

    Yes

    cn-shanghai

    The region ID. For more information, see Supported regions.

    apiPath

    String

    Yes

    /iot-cn-npk1v******/system/query/hist_dev_cnt_stat

    To find the API path, go to the API list in Data Service, click View next to an API to open its details page, and find the API Path value. For more information, see Manage and use APIs.

    pageNum

    Integer

    Required when pagination is enabled

    1

    The page number.

    pageSize

    Integer

    Required when pagination is enabled

    100

    The number of results per page. The maximum value is 100.

    iotInstanceId

    String

    Yes

    iot-cn-npk1v******

    The instance ID.

  • Business-related request parameters:

    Parameter

    Type

    Required

    Description

    Related code

    fieldName

    String

    Yes

    The name of the request parameter.

     condition.fieldName = '__instance_id__';

    operate

    String

    Yes

    The operator for the request parameter. Valid values:

    • =: Specifies that the request parameter must be a specific value.

    • BETWEEN: Specifies that the request parameter must be within a specific range.

    • IN: Specifies that the request parameter can be one of multiple values.

    • !=: Specifies that the request parameter cannot be a specific value.

     condition.operate = '=';

    value

    String

    No

    The value of the request parameter.

    Important

    This parameter is required if the operate parameter is not set to BETWEEN.

     condition.value = 'iot-public';

    betweenStart

    String

    No

    The start of the range for the request parameter.

    Important

    This parameter is required if the operate parameter is set to BETWEEN.

     condition.betweenStart = '0';

    betweenEnd

    String

    No

    The end of the range for the request parameter.

    Important

    This parameter is required if the operate parameter is set to BETWEEN.

     condition.betweenEnd = '1000';

    Each request parameter corresponds to one condition. You can view the request parameters for an API on its details page and configure the corresponding number of condition objects. For information about how to view API request parameters, see Manage APIs.

    In this example, the API has three request parameters (__instance_id__, entityId, and statDate), which correspond to condition, condition1, and condition2, respectively.

Results

  • Success:

    View detailed descriptions of the response parameters on the API details page. For more information, see Manage and use APIs.

    The following example shows a successful API call. The response contains statistics for the number of devices in the public instance, calculated from February 21, 2021, up 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:

    The error code in the response indicates the cause of the failure. For more information about error codes, see error codes.

    The following example shows a failed API call caused by an invalid request parameter, __instance_idd__. To fix this error, change the parameter to __instance_id__ and retry the call.

    >node API.js
    Error: InvalidParameter: code: 400, invalid parameter:redundant query param : __instance_idd__ request id: 43432743-BA23-480C-B33A-DCDA xxx
        at Object.newError (xxx\node_modules\@alicloud\tea-typescript\dist\tea.js:195:12)
        at Client.doRPCRequest (xxx\node_modules\@alicloud\openapi-client\dist\client.js:284:32)
        at processTicksAndRejections (internal/process/task_queues.js:93:5)
        at async Client.listAnalyticsDataWithOptions (xxx\node_modules\@alicloud\iot20180120\dist\client.js:24995:26)
        at async Client.listAnalyticsData (xxx\node_modules\@alicloud\iot20180120\dist\client.js:24999:16)
        at async main (xxx\API.js:50:26)