All Products
Search
Document Center

Alibaba Cloud SDK:Integrate Alibaba Cloud SDK V2.0 for Node.js

Last Updated:Oct 11, 2024

To integrate Alibaba Cloud SDK, you must perform the following steps: install Alibaba Cloud SDK, configure an access credential, and write code for calling API operations. This topic describes how to integrate Alibaba Cloud SDK. In this example, Alibaba Cloud SDK for Node.js is used to call the SendSms operation of Short Message Service (SMS) to send a text message.

Prerequisites

The version of Node.js to be installed is 8.x or later.

1. Install the SDK for Node.js

Alibaba Cloud SDK allows you to make generic and specialized calls. For more information, see Generic calls and specialized calls. The SDK that you need to install varies based on the call type.

Install the SDK for specialized calls

Alibaba Cloud SDK V2.0 incorporates the main API logic, such as parameter processing, request assembly, and response processing. You can make API requests by installing the SDK of an Alibaba Cloud service as a dependency.

  1. Log on to SDK Center and select the service whose SDK you want to use. In this example, Short Message Service (SMS) is selected.

  2. On the Short Message Service page, select TypeScript in the All languages section. On the Quick Start tab, obtain the installation method of Short Message Service (SMS) SDK.image

Install the SDK for generic calls

You do not need to install the SDK of an Alibaba Cloud service to make generic calls. You need to only import the @alicloud/openapi-client core package. For more information about the latest core package of the SDK, see @alicloud/openapi-client. Sample code:

npm i @alicloud/openapi-client

2. Configure an access credential

To call API operations of an Alibaba Cloud service, you must configure an access credential, such as an AccessKey pair. For more information, see the "Credential" section of the Identity, credential, and authorization topic. To prevent AccessKey pair leaks, you can record the AccessKey pair in environment variables. For more information about other security solutions, see Credential security solutions. In this example, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.

Configure environment variables in Linux and macOS

Configure environment variables by using the export command

Important

The temporary environment variables configured by using the export command are valid only for the current session. After you exit the session, the configured environment variables become invalid. To configure permanent environment variables, you can add the export command to the startup configuration file of the corresponding operating system.

  • Configure the AccessKey ID and press Enter.

    # Replace <ACCESS_KEY_ID> with your AccessKey ID. 
    export ALIBABA_CLOUD_ACCESS_KEY_ID=<ACCESS_KEY_ID>
  • Configure the AccessKey secret and press Enter.

    # Replace <ACCESS_KEY_SECRET> with your AccessKey secret. 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET>
  • Check whether the configuration is successful.

    Run the echo $ALIBABA_CLOUD_ACCESS_KEY_ID command. If the valid AccessKey ID is returned, the environment variables are configured.

Configure environment variables in Windows

Use GUI

  • Procedure

    If you want to use GUI to configure environment variables in Windows 10, perform the following steps:

    On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section. Then, configure the variables described in the following table.

    Variable

    Example

    AccessKey ID

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

    • Variable value: LTAI4GDty8ab9W4Y1D****

    AccessKey Secret

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

    • Variable value: IrVTNZNy5yQelTETg0cZML3TQn****

  • Check whether the configuration is successful.

    On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

Use CMD

  • Procedure

    Open a Command Prompt window as an administrator and run the following commands to add environment variables in the operating system:

    setx ALIBABA_CLOUD_ACCESS_KEY_ID LTAI4GDty8ab9W4Y1D**** /M
    setx ALIBABA_CLOUD_ACCESS_KEY_SECRET IrVTNZNy5yQelTETg0cZML3TQn**** /M

    /M indicates that the environment variable is of system level. You can choose not to use this parameter when you configure a user-level environment variable.

  • Check whether the configuration is successful.

    On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

Use Windows PowerShell

In PowerShell, configure new environment variables. The environment variables apply to all new sessions.

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::User)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::User)

Configure environment variables for all users. You must run the following commands as an administrator.

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::Machine)

Configure temporary environment variables. The environment variables apply only to the current session.

$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "LTAI4GDty8ab9W4Y1D****"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "IrVTNZNy5yQelTETg0cZML3TQn****"

In PowerShell, run the Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_ID and Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_SECRET commands. If the valid AccessKey pair is returned, the configuration is successful.

3. Call an API operation

In this example, a specialized call is made. For more information about how to make a generic call, see Generic calls.

3.1 Initialize a request client

You can use multiple methods to initialize a request client. For more information, see Manage access credentials. In this example, an AccessKey pair is used to initialize a request client.

TypeScript

import Dysmsapi20180501, * as $Dysmsapi20180501 from '@alicloud/dysmsapi20180501';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';

export default class Client {

  static createClient(): Dysmsapi20180501 {
    let config = new $OpenApi.Config({
      // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // See https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20180501(config);
  }
}

JavaScript

const Dysmsapi20180501 = require('@alicloud/dysmsapi20180501');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');

class Client {

  static createClient() {
    let config = new OpenApi.Config({
      // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // See https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20180501.default(config);
  }
}

3.2 Create a request object and configure runtime configurations

In most cases, you can create a request object and specify the parameters based on your business requirements. You can also customize runtime configurations.

// Create a request object and specify the parameters.
let sendMessageToGlobeRequest = new Dysmsapi20180501.SendMessageToGlobeRequest({
    to: '<YOUR_VALUE>',
    from: '<YOUR_VALUE>',
    message: '<YOUR_VALUE>',
});
// Create a runtime configuration object.
let runtime = new Util.RuntimeOptions({});

3.3 Initiate an API request

In Alibaba Cloud SDK V2.0, the client of each Alibaba Cloud service contains all the API operations provided by the service. In addition, Alibaba Cloud SDK V2.0 provides three methods to define each API operation. This design aims to improve the flexibility and efficiency of development, and ensure that developers can call API operations in an optimal way based on their project requirements.

Note

The name of the API operation is in lowercase letters.

  • <API operation>: uses the default runtime configurations to initiate a request. You do not need to specify runtime parameters.

    TypeScript

    import Dysmsapi20180501, * as $Dysmsapi20180501 from '@alicloud/dysmsapi20180501';
    import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
    import Util, * as $Util from '@alicloud/tea-util';
    
    export default class Client {
    
      static createClient(): Dysmsapi20180501 {
        let config = new $OpenApi.Config({
          // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. 
          accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
          // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. 
          accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
        });
        // The endpoint of SMS. For more information, visit https://api.alibabacloud.com/product/Dysmsapi.
        config.endpoint = `dysmsapi.aliyuncs.com`;
        return new Dysmsapi20180501(config);
      }
    
      static async main(): Promise<void> {
        let client = Client.createClient();
        // Create a request object and specify parameters.
        let sendMessageToGlobeRequest = new $Dysmsapi20180501.SendMessageToGlobeRequest({
          to: "<YOUR_VALUE>",
          from: "<YOUR_VALUE>",
          message: "<YOUR_VALUE>",
        });
        try {
          // Initiate the request.  
          await client.sendMessageToGlobe(sendMessageToGlobeRequest);
        } catch (error) {
          // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. 
          // Return error messages.
          console.log(error.message);
          // The URL of the corresponding error diagnostics.
          console.log(error.data["Recommend"]);
        }    
      }
    }
    
    Client.main();
    

    JavaScript

    const Dysmsapi20180501 = require('@alicloud/dysmsapi20180501');
    const OpenApi = require('@alicloud/openapi-client');
    const Util = require('@alicloud/tea-util');
    
    class Client {
    
      static createClient() {
        let config = new OpenApi.Config({
          // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. 
          accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
          // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. 
          accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
        });
        // The endpoint of SMS. For more information, visit https://api.alibabacloud.com/product/Dysmsapi.
        config.endpoint = `dysmsapi.aliyuncs.com`;
        return new Dysmsapi20180501.default(config);
      }
    
      static async main() {
        // Create a request object and specify parameters.
        let client = Client.createClient();
        let sendMessageToGlobeRequest = new Dysmsapi20180501.SendMessageToGlobeRequest({
          to: '<YOUR_VALUE>',
          from: '<YOUR_VALUE>',
          message: '<YOUR_VALUE>',
        });
        try {
          // Initiate the request.
          await client.sendMessageToGlobe(sendMessageToGlobeRequest);
        } catch (error) {
          // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. 
          // Return error messages.
          console.log(error.message);
          // The URL of the corresponding error diagnostics.
          console.log(error.data["Recommend"]);
          Util.default.assertAsString(error.message);
        }    
      }
    }
    
    exports.Client = Client;
    Client.main();
    
  • <API operation>WithOptions: uses the custom runtime configurations to initiate a request. For more information, see Advanced configuration.

    TypeScript

    import Dysmsapi20180501, * as $Dysmsapi20180501 from '@alicloud/dysmsapi20180501';
    import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
    import Util, * as $Util from '@alicloud/tea-util';
    
    export default class Client {
    
      static createClient(): Dysmsapi20180501 {
        let config = new $OpenApi.Config({
          // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. 
          accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
          // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. 
          accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
        });
        // The endpoint of SMS. For more information, visit https://api.alibabacloud.com/product/Dysmsapi.
        config.endpoint = `dysmsapi.aliyuncs.com`;
        return new Dysmsapi20180501(config);
      }
    
      static async main(): Promise<void> {
        let client = Client.createClient();
        // Create a request object and specify parameters.
        let sendMessageToGlobeRequest = new $Dysmsapi20180501.SendMessageToGlobeRequest({
          to: "<YOUR_VALUE>",
          from: "<YOUR_VALUE>",
          message: "<YOUR_VALUE>",
        });
        // Create a runtime configuration object.
        let runtime = new $Util.RuntimeOptions({ });
        try {
          // Initiate the request.  
          await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
        } catch (error) {
          // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. 
          // Return error messages.
          console.log(error.message);
          // The URL of the corresponding error diagnostics.
          console.log(error.data["Recommend"]);
        }    
      }
    }
    
    Client.main();
    

    JavaScript

    const Dysmsapi20180501 = require('@alicloud/dysmsapi20180501');
    const OpenApi = require('@alicloud/openapi-client');
    const Util = require('@alicloud/tea-util');
    
    class Client {
    
      static createClient() {
        let config = new OpenApi.Config({
          // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. 
          accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
          // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. 
          accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
        });
        // The endpoint of SMS. For more information, visit https://api.alibabacloud.com/product/Dysmsapi.
        config.endpoint = `dysmsapi.aliyuncs.com`;
        return new Dysmsapi20180501.default(config);
      }
    
      static async main() {
        // Create a request object and specify parameters.
        let client = Client.createClient();
        let sendMessageToGlobeRequest = new Dysmsapi20180501.SendMessageToGlobeRequest({
          to: '<YOUR_VALUE>',
          from: '<YOUR_VALUE>',
          message: '<YOUR_VALUE>',
        });
        // Create a runtime configuration object.
        let runtime = new Util.RuntimeOptions({ });
        try {
          // Initiate the request.
          await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
        } catch (error) {
          // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. 
          // Return error messages.
          console.log(error.message);
          // The URL of the corresponding error diagnostics.
          console.log(error.data["Recommend"]);
          Util.default.assertAsString(error.message);
        }    
      }
    }
    
    exports.Client = Client;
    Client.main();
    
  • <API operation>Advance: used for API operations that require file uploading. By default, you must specify runtime parameters. The following sample code provides examples on how to initiate a request to upload a file and call an API operation to use the human face and body recognition feature of Vision Intelligent Application Programming Interface Platform (VIAPI).

    // The dependency for the human face and body recognition feature.
    npm install @alicloud/facebody20191230@4.0.8

    TypeScript

    import Facebody20191230, * as $Facebody20191230 from '@alicloud/facebody20191230';
    import * as $OpenApi from '@alicloud/openapi-client';
    import * as $Util from '@alicloud/tea-util';
    import {createReadStream} from 'fs';
    import Credential from '@alicloud/credentials';
    
    export default class Client {
      static async main(): Promise<void> {
        // Use the default credential to initialize a Credentials client.
        const credentialClient = new Credential();
        const facebodyConfig = new $OpenApi.Config({
          // Use the SDK Credentials package to configure a credential.
          credential: credentialClient,
          // Specify the region in which you want to access the human face and body recognition feature. Only the China (Shanghai) region is supported by the feature.
          regionId: 'cn-shanghai',
        });
        const facebodyClient = new Facebody20191230(facebodyConfig);
        const request = new $Facebody20191230.DetectBodyCountAdvanceRequest({
          imageURLObject: createReadStream('<YOUR-FILE-PATH>'),
        });
        // Construct the runtime configuration object and specify runtime parameters. 
        const runtime = new $Util.RuntimeOptions({});
        const resp = await facebodyClient.DetectBodyCountAdvance(request, runtime);
        console.log(resp.headers);
        console.log(resp.body);
      }
    }
    

    JavaScript

    const { default: Facebody20191230, DetectBodyCountAdvanceRequest } = require('@alicloud/facebody20191230');
    const { Config } = require('@alicloud/openapi-client');
    const { RuntimeOptions } = require('@alicloud/tea-util');
    const { createReadStream } = require('fs');
    const { default: Credential } = require('@alicloud/credentials')
    
    async function main() {
      const facebodyConfig = new Config({
        credential: new Credential(),
        // Specify the region in which you want to access the human face and body recognition feature. Only the China (Shanghai) region is supported by the feature.
        regionId: 'cn-shanghai'
      });
      const facebodyClient = new Facebody20191230(facebodyConfig);
      const request = new DetectBodyCountAdvanceRequest({
        imageURLObject: createReadStream('<YOUR-FILE-PATH>'),
      });
      // Construct the runtime configuration object and specify runtime parameters. 
      const runtime = new RuntimeOptions({});
      const resp = await facebodyClient.detectBodyCountAdvance(request, runtime);
      console.log(resp.headers);
      console.log(resp.body);
    }
    main();