Node.js SDK guide

Updated at:

IoT Platform provides a cloud SDK for TypeScript. Learn how to install and configure the Node.js SDK and call cloud APIs.

Install the SDK

  1. Install the Node.js developer environment.

    The Node.js SDK requires Node.js version 8.x or later.

  2. Install the OpenAPI core library for the SDK.

    Run the following npm command to install the dependency and add it to the `package.json` file.

    npm install @alicloud/openapi-client -S
  3. Install the IoT Node.js SDK.

    Run the following npm command to install the SDK. For example, to install version 3.0.8:

    npm install --save @alicloud/iot20180120@3.0.8

    For information about the Node.js SDK source code, see alibabacloud-typescript-sdk.

Initialize the SDK

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

  2. Create an instance of the Client object named client. Call the Iot(config) method to load the SDK configuration and initialize the 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.

import Iot, * as $Iot from '@alicloud/iot20180120';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
let config = new $OpenApi.Config({ });
// Your AccessKey ID.
config.accessKeyId = process.env.ACCESS_KEY_ID;
// Your AccessKey secret.
config.accessKeySecret = process.env.ACCESS_KEY_SECRET;
// Your region ID.
config.regionId = "cn-shanghai";
let client = new Iot(config);

Parameter

Description

regionId

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 information about how to configure HTTP requests, proxies, timeouts, and retries for the SDK client, see Alibaba Cloud Upgraded Node.js SDK User Guide.

Make a call

The IoT Platform cloud SDK encapsulates two classes for each API: ${API name}+"Request" and ${API name}+"Response". These classes contain the API request and response.

Steps

  1. You have initialized the SDK client. For more information, see SDK Initialization.

  2. Create an instance of the ${API name}+"Request" class for the target API and name the instance request.

  3. Use the request object to set the required request parameters for the API.

  4. Create an instance of the ${API name}+"Response" class named response. Call the ${API name}(request) method of the client object to send the request. The response includes the body and headers from the server.

  5. Access specific return parameters through the response.body.${return parameter name} property.

    For example, response.body.success indicates whether the call succeeded. Other common return parameters include RequestId, ErrorMessage, and Code.

  6. Use the catch() method to handle exceptions.

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.

try {
    let client = Client.createClient("${accessKey}", "${accessKeySecret}");
    let request = new $Iot.PubRequest({
        // The ID of the IoT Platform instance.
        iotInstanceId: "${iotInstanceId}",
        // The ProductKey of the product.
        productKey: "${productKey}",
        // The message body to send. The value must be Base64-encoded.
        messageContent: "eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=",
        // The custom topic of the device that receives the message.
        topicFullName: "/${productKey}/${deviceName}/user/get",
        // The method to send the message. QoS 0 and QoS 1 are supported.
        qos: 0,
    });
    let response = await client.pub(request);
    Console.log(Util.toJSONString($tea.toMap(response)));
} catch (error) {
    Console.log(error.message);
}

Complete code example

Note

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

import Iot, * as $Iot from '@alicloud/iot20180120';
import Util from '@alicloud/tea-util';
import Env from '@alicloud/darabonba-env';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Console from '@alicloud/tea-console';
import * as $tea from '@alicloud/tea-typescript';


export default class Client {
  /**
   * Use an AccessKey pair (AccessKey ID and AccessKey secret) to initialize a client.
   * @param accessKeyId
   * @param accessKeySecret
   * @param regionId
   * @return Client
   * @throws Exception
   */
  static createClient(): Iot {
    let config = new $OpenApi.Config({ });
    // Your AccessKey ID.
    config.accessKeyId = process.env.ACCESS_KEY_ID;
    // Your AccessKey secret.
    config.accessKeySecret = process.env.ACCESS_KEY_SECRET;
    // Your region ID.
    config.regionId = "cn-shanghai";
    return new Iot(config);
   }


  static async main(args: string[]): Promise<void> {
    try {
      let client = Client.createClient("${accessKey}", "${accessKeySecret}");
      let request = new $Iot.PubRequest({
        // The ID of the IoT Platform instance.
        iotInstanceId: "${iotInstanceId}",
        // The ProductKey of the product.
        productKey: "${productKey}",
        // The message body to send. This is a Base64-encoded "hello world" string.
        messageContent: "eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=",
        // The custom topic of the device that receives the message.
        topicFullName: "/${productKey}/${deviceName}/user/get",
        // The method to send the message. QoS 0 and QoS 1 are supported.
        qos: 0,
      });
      let response = await client.pub(request);
      Console.log(response.body.success);
      Console.log(response.body.requestId);
    } catch (error) {
      Console.log(error.message);
    }    
  }
}

Client.main(process.argv.slice(2));

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.