All Products
Search
Document Center

IoT Platform:Use IoT Platform SDK for Node.js

Last Updated:Oct 22, 2023

IoT Platform provides an SDK for Node.js. This topic describes how to install and configure IoT Platform SDK for Node.js. This topic also provides sample code on how to use the SDK to call API operations of IoT Platform.

Install the SDK

  1. Install a Node.js development environment.

    The upgraded IoT Platform SDK for Node.js is developed based on the Node.js environment. You must install Node.js 8.x or later.

  2. Install Alibaba Cloud SDK for Node.js.

    You can use npm to manage your dependencies. Run the following command to add the dependency to the package.json file:

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

    Run the following command to install the SDK of the 3.0.8 version:

    npm install --save @alicloud/iot20180120@3.0.8

    For information about the source code of the SDK for Node.js, visit alibabacloud-typescript-sdk.

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 instance and call the Iot(config) method to load the SDK initialization information from the config object.

For example, if you want to use the SDK in the China (Shanghai) region, you can use the following code to initialize the SDK. In the production environment, you must select the region where IoT Platform is activated.

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;
// The region ID. 
config.regionId = "cn-shanghai";
let client = new Iot(config);

Parameter

Description

regionId

The ID of the region where your IoT Platform instance resides. The region ID is used in the endpoint for service access. The endpoint is in the iot.${RegionId}.aliyuncs.com format.

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

For more information about the formats of region IDs, see Supported regions.

Initiate a request

The SDK encapsulates two classes for each API operation. The class whose name is in the ${API name}+"Request" format indicates the request, and the class whose name is in the ${API name}+"Response" format indicates the response.

Procedure

  1. Initialize the SDK. For more information, see the Initialize the SDK section of this topic.

  2. Create an API request by generating a request instance of the ${API operation name}+"Request" class.

  3. Use the request instance to specify the request parameters.

  4. Create a response instance of the ${API operation name}+"Response" class to obtain the response. Call the ${API operation name}(request) method of the client instance to obtain the response to the API request. The response includes the body and headers returned by the server.

  5. Call the response.body.${Response parameter} method to obtain the values of response parameters.

    For example, you can call the response.body.success method to obtain the Success parameter. This parameter is a common response parameter that indicates whether the request is successful. Common response parameters also include RequestId, ErrorMessage, and Code.

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

For more information about the API operations of IoT Platform, see List of operations by function. For more information about the request parameters and response parameters of each API operation, see the API reference.

The following example shows how to call the Pub operation to publish a message to a topic. For more information about request parameters, see Pub.

Important

In the following sample code, ${iotInstanceId} specifies the ID of an instance. You can view the ID of the instance on the Overview page in the IoT Platform console.

  • If your instance has an ID, you must specify the ID for this parameter. Otherwise, the call fails.

  • If no Overview page or ID is generated for your instance, you do not need to configure this parameter. You must delete the request code that is related to the IotInstanceId parameter or specify an empty string ("") for the parameter. Otherwise, the call fails.

For more information about IoT Platform instances, see Overview. For more information about how to purchase an instance, see Purchase Enterprise Edition instances. For more information, see FAQ about IoT Platform instances.

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 be sent. It must be encoded in Base64. 
        messageContent: "eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=",
        // The custom topic that is used to publish the message. 
        topicFullName: "/${productKey}/${deviceName}/user/get",
        // The message sending mode. IoT Platform SDK supports QoS 0 and QoS 1. 
        qos: 0,
    });
    let response = await client.pub(request);
    Console.log(Util.toJSONString($tea.toMap(response)));
} catch (error) {
    Console.log(error.message);
}

Sample code

Note

You can replace the values of the preceding parameters with actual values based on your business scenario.

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 your AccessKey ID and AccessKey secret to initialize the 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;
    // The 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 that you want to send. Encode "hello world" in Base64 as a string. 
        messageContent: "eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=",
        // The custom topic that is used to publish the message. 
        topicFullName: "/${productKey}/${deviceName}/user/get",
        // The message sending mode. IoT Platform SDK supports QoS 0 and QoS 1. 
        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 view or download the sample code of API operations in IoT Platform SDK Sample Center. Sample code of SDKs for Java, Python, PHP, Node.js, Go, C++, and .NET is provided.

Alibaba Cloud OpenAPI Explorer provides online debugging tools for API operations. On the API Debugging page, you can search for API operations, call API operations, and generate sample code for API operations of different SDKs. On the right side of the page, you can view the sample code of an SDK on the Sample Code tab. On the Debugging Result tab, you can view the actual request URL and response in the JSON format.