All Products
Search
Document Center

Alibaba Cloud SDK:Integrate the SDK

Last Updated:Jun 02, 2026

Integrate the SDK to call OpenAPI operations. The process has three steps: import the SDK, set access credentials, and call the API.

Environment requirements

Node.js >= 8.x

Import the SDK

  1. Log on to SDK Center and select the product for the API you want to call, such as Short Message Service (SMS).

  2. On the Installation page, and set All Languages to TypeScript. Then, on the Quick Start tab, you can find the SDK installation instructions for Short Message Service (SMS).image

Set access credentials

Calling OpenAPI operations requires access credentials such as AccessKey or Security Token Service (STS) token. Store credentials in environment variables to prevent leaks. For best practices, see Securely use access credentials. The examples below use the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Configuration method in Linux and macOS

Configure environment variables using the export command

Important

A temporary environment variable set using the export command is valid only for the current session. The variable is cleared when the session ends. For long-term retention (LTR), add the export command to the startup configuration file of your operating system.

  • Configure the AccessKey ID and press Enter.

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

    # Replace yourAccessKeySecret with your AccessKey secret.
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecret
  • Verify the configuration.

    Run the echo $ALIBABA_CLOUD_ACCESS_KEY_ID command. If the command returns the correct AccessKey ID, the configuration is successful.

Configuration method in Windows

Use the graphical user interface (GUI)

  • Procedure

    The following steps describe how to set environment variables using the GUI in Windows 10.

    On your desktop, right-click This PC and choose Properties > Advanced system settings > Environment Variables > New under System variables or User variables. Then, complete the configuration.

    Variable

    Example value

    AccessKey ID

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

    • Variable value: yourAccessKeyID

    AccessKey Secret

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

    • Variable value: yourAccessKeySecret

  • Test the configuration

    Click Start (or use the Win+R keyboard shortcut), click Run, enter `cmd`, and then click OK (or press Enter) to open the command prompt. Run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the commands return the correct AccessKey, the configuration is successful.

Use the command prompt (CMD)

  • Procedure

    Open the command prompt as an administrator and run the following commands to add new environment variables to the system.

    setx ALIBABA_CLOUD_ACCESS_KEY_ID yourAccessKeyID /M
    setx ALIBABA_CLOUD_ACCESS_KEY_SECRET yourAccessKeySecret /M

    The /M parameter indicates a system environment variable. You can omit this parameter when you set a user environment variable.

  • Test the configuration

    Click Start (or use the Win+R keyboard shortcut), click Run, enter `cmd`, and then click OK (or press Enter) to open the command prompt. Run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the commands return the correct AccessKey, the configuration is successful.

Using Windows PowerShell

In PowerShell, you can set new environment variables that are valid for all new sessions:

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::User)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::User)

To set environment variables for all users, you must have administrative permissions:

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::Machine)

You can set temporary environment variables that are valid only for the current session:

$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "yourAccessKeyID"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "yourAccessKeySecret"

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

Use the SDK

This topic provides an example of how to call the or SendMessageToGlobe API operation of Short Message Service (SMS). For the API reference for the or SendMessageToGlobe API operation, see or SendMessageToGlobe.

1. Initialize the request client

All OpenAPI calls go through a request client. This example initializes a client with an AccessKey pair. For other initialization methods, see Manage access credentials.

Important
  • Client objects, such as Dysmsapi20180501 and instances, are thread-safe and can be used in a multi-threaded environment without the need to create a separate instance for each thread.

  • Avoid creating client objects repeatedly with `new`. Use the singleton pattern so that only one client instance exists per credential and endpoint throughout the application lifecycle.

TypeScript example

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 set.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // For more information about the endpoint, see https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20180501(config);
  }
}

Node.js example

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. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // For more information about the endpoint, see https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20180501.default(config);
  }
}

2. Create the request object

Pass parameters through the SDK request object, named <OpenAPI Name>Request (for example, SendSmsRequest). For parameter details, see the API reference: SendMessageToGlobe.

Note

If an API has no request parameters, skip this step. For example, DescribeCdnSubList requires no request object.

TypeScript example

 // Create request object and set required input parameters
 let sendMessageToGlobeRequest = new $Dysmsapi20180501.SendMessageToGlobeRequest({
      // Please replace with the actual recipient number.
      to: "<YOUR_VALUE>",
      // Please replace with the actual SMS content.
      message: "<YOUR_VALUE>",
    });

Node.js example

// Create request object and set required input parameters
let sendMessageToGlobeRequest = new Dysmsapi20180501.SendMessageToGlobeRequest({
    // Please replace with the actual recipient number.
    to: '<YOUR_VALUE>',
    // Please replace with the actual SMS content.
    message: '<YOUR_VALUE>',
});

3. Send the request

Call the client's <operationName>WithOptions function, where <operationName> is the API name in camel case. This function takes a request object and runtime parameters (timeout, proxy, etc.). See Advanced configurations.

Note

If an API has no request parameters, pass only the runtime options. For example, DescribeCdnSubList requires only runtime parameters.

TypeScript example

// Create runtime parameters.
let runtime = new $Util.RuntimeOptions({ });
let client = Client.createClient();
// Send a request.
await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);

Node.js example

// Create runtime parameters.
let runtime = new Util.RuntimeOptions({ });
let client = Client.createClient();
// Send a request.
await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);

4. Handle exceptions

The V2.0 Node.js SDK throws two exception types:

  • UnretryableError: Thrown after max retries are exhausted, typically due to network issues. Retrieve the last request via err.data.lastRequest.

  • ResponseError: Indicates a server-side error returned by the API.

See Exception handling.

Important

Always handle exceptions — propagate, log, or recover. Never silently ignore them.

Click to view the complete code example

SendMessageToGlobe API call example

TypeScript example

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 set.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // For more information about the endpoint, see 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 set the input parameters.
    let sendMessageToGlobeRequest = new $Dysmsapi20180501.SendMessageToGlobeRequest({
      to: "<YOUR_VALUE>",
      from: "<YOUR_VALUE>",
      message: "<YOUR_VALUE>",
    });
    let runtime = new $Util.RuntimeOptions({ });
    try {
      // Send the request.
      await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
    } catch (error) {
      // This is for demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
      // Error message
      console.log(error.message);
      // Diagnostic address
      console.log(error.data["Recommend"]);
    }    
  }
}

Client.main();

Node.js example

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 set.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // For more information about the endpoint, see https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20180501.default(config);
  }

  static async main() {
    // Create a request object and set the input parameters.
    let client = Client.createClient();
    let sendMessageToGlobeRequest = new Dysmsapi20180501.SendMessageToGlobeRequest({
      to: '<YOUR_VALUE>',
      from: '<YOUR_VALUE>',
      message: '<YOUR_VALUE>',
    });
    let runtime = new Util.RuntimeOptions({ });
    try {
      // Send the request.
      await client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
    } catch (error) {
      // This is for demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
      // Error message
      console.log(error.message);
      // Diagnostic address
      console.log(error.data["Recommend"]);
      Util.default.assertAsString(error.message);
    }    
  }
}

exports.Client = Client;
Client.main();

File upload with Advance operations

Some APIs (such as image search and Visual Intelligence) do not accept local file paths directly. Use the Advance operation to upload files via a stream. The SDK stores the file temporarily in an OSS bucket in the cn-shanghai region, and the service reads it from there. This example uses the DetectBodyCount operation of Visual Intelligence API.

Important

Temporary files stored in Alibaba Cloud OSS are cleared periodically.

  1. Initialize the request client

    Set both regionId and endpoint to the same region. The regionId determines where the temporary OSS file is stored. If you omit regionId, a region mismatch between the product and the OSS bucket causes timeouts.

    TypeScript example

    function createClient(): facebody20191230 {
        let config = new $OpenApi.Config({
            // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
            accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
            accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
        });
        // The endpoint and regionId must be for the same region.
        config.regionId = 'cn-shanghai';
        config.endpoint = 'facebody.cn-shanghai.aliyuncs.com';
        return new facebody20191230(config);
    }

    Node.js example

    function createClient() {
      let config = new OpenApi.Config({
        // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
        accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
        // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
        accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
      });
      // The endpoint and regionId must be for the same region.
      config.regionId = 'cn-shanghai';
      config.endpoint = 'facebody.cn-shanghai.aliyuncs.com';
      return new facebody20191230.default(config);
    }
  2. Create the request object

    Create a <OpenAPIName>AdvanceRequest object to pass the file stream. The parameter name for the file stream is ImageURLObject.

    TypeScript example

        // Read the file as a file stream.
        const filePath = '<FILE_PATH>';  // Replace this with the actual file path.
        // Check if the file exists.
        if (!fs.existsSync(filePath)) {
            console.error('File does not exist:', filePath);
            return;
        }
        // Create a stream and listen for stream errors.
        const fileStream = fs.createReadStream(filePath).on('error', (err) => {
            console.error('Stream error:', err);
            process.exit(1);
        });
    
        let detectBodyCountAdvanceRequest = new $facebody20191230.DetectBodyCountAdvanceRequest({
          imageURLObject: fileStream,
        });

    Node.js example

        // Read the file as a file stream.
        const filePath = '<FILE_PATH>';  // Replace this with the actual file path.
        // Check if the file exists.
        if (!fs.existsSync(filePath)) {
            console.error('File does not exist:', filePath);
            return;
        }
        // Create a stream and listen for stream errors.
        const fileStream = fs.createReadStream(filePath).on('error', (err) => {
            console.error('Stream error:', err);
            process.exit(1);
        });
    
        let detectBodyCountAdvanceRequest = new facebody20191230.DetectBodyCountAdvanceRequest({
            imageURLObject: fileStream,
        });
  3. Send the request

    Call the <operationName>Advance function to send the request.

    TypeScript example

    // Configure runtime parameters.
    let runtime = new $Util.RuntimeOptions({ });
    let client = Client.createClient();
    // Send the request.
    await client.detectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime);

    Node.js example

     // Configure runtime parameters.
     let runtime = new Util.RuntimeOptions({ });
     let client = Client.createClient();
     // Send the request.
     await client.detectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime);  

Click to view the complete code example

TypeScript example

import { default as facebody20191230 } from '@alicloud/facebody20191230';
import * as $facebody20191230 from '@alicloud/facebody20191230';
import * as $OpenApi from '@alicloud/openapi-client';
import * as $Util from '@alicloud/tea-util';
import * as fs from "fs";

export default class Client {
    static createClient(): facebody20191230 {
        let config = new $OpenApi.Config({
            // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
            accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
            accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
        });
        config.regionId = 'cn-shanghai';
        config.endpoint = 'facebody.cn-shanghai.aliyuncs.com';
        return new facebody20191230(config);
    }

    static async main(): Promise<void> {
        let client = Client.createClient();

        // Read the file as a file stream.
        const filePath = '<FILE_PATH>';  // Replace this with the actual file path.
        // Check if the file exists.
        if (!fs.existsSync(filePath)) {
            console.error('File does not exist:', filePath);
            return;
        }
        // Create a stream and listen for stream errors.
        const fileStream = fs.createReadStream(filePath).on('error', (err) => {
            console.error('Stream error:', err);
            process.exit(1);
        });

        let detectBodyCountAdvanceRequest = new $facebody20191230.DetectBodyCountAdvanceRequest({
            imageURLObject: fileStream,
        });
        let runtime = new $Util.RuntimeOptions({});
        try {
            // Send the request.
            const res = await client.detectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime);
            console.log(res);
        } catch (error) {
            if (error instanceof Error) {
                console.error('Error message:', error.message);
                const data = (error as any)?.data?.Recommend;
                if (typeof data === 'string') {
                    console.log('Diagnostic suggestion:', data);
                }
            }
        }
    }
}

Client.main();

Node.js example

'use strict';
const facebody20191230 = require('@alicloud/facebody20191230');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const fs = require('fs');

class Client {
  static createClient() {
    let config = new OpenApi.Config({
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    config.regionId = 'cn-shanghai';
    config.endpoint = 'facebody.cn-shanghai.aliyuncs.com';
    return new facebody20191230.default(config);
  }

  static async main() {
    let client = Client.createClient();
    // Read the file as a file stream.
    const filePath = '<FILE_PATH>';  // Replace this with the actual file path.
    // Check if the file exists.
    if (!fs.existsSync(filePath)) {
      console.error('File does not exist:', filePath);
      return;
    }
    // Create a stream and listen for stream errors.
    const fileStream = fs.createReadStream(filePath).on('error', (err) => {
      console.error('Stream error:', err);
      process.exit(1);
    });
    // Configure request parameters.
    let detectBodyCountAdvanceRequest = new facebody20191230.DetectBodyCountAdvanceRequest({
      imageURLObject: fileStream,
    });
    let runtime = new Util.RuntimeOptions({});
    try {
      // Send the request.
      const res = await client.detectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime);
      console.log(res);
    } catch (error) {
      // This is for demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
      console.log(error);
    }
  }
}

exports.Client = Client;
Client.main();

FAQ

  1. "You are not authorized to perform this operation" error when calling an API

    Cause and solution

    Cause: The RAM user associated with your AccessKey does not have the required permissions to call the API.

    Solution: Grant the required API permissions to the RAM user. See Manage RAM user permissions.

    For example, if you receive this error when calling or SendMessageToGlobe, you can create the following custom permission policy and attach it to the RAM user.

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendMessageToGlobe",
          "Resource": "*"
        }
      ]
    }
  2. "triggerUncaughtException Error: getaddrinfo ENOTFOUND" error (endpoint issue)

    Cause and solution

    Cause: The specified endpoint is not supported by the OpenAPI operation that you are calling.

    Solution: Fix the endpoint using Endpoint configuration and retry.

  3. "Cannot read properties of undefined (reading 'getCredential')" or "InvalidAccessKeyId.NotFound: code: 404" error

    Cause and solution

    Cause: The AccessKey was not passed correctly.

    Solution: Verify that the AccessKey is passed correctly during client initialization. process.env("XXX") reads the value of XXX from environment variables.

For other common errors, see FAQ.