Integrate the SDK

更新时间:
复制 MD 格式

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, set SDK Generation to V2.0, 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 SendSms or API operation of Short Message Service (SMS). For the API reference for the SendSms or API operation, see SendSms or .

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 and Dysmsapi20170525 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 Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';

export default class Client {

  static createClient(): Dysmsapi20170525 {
    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'],
    });
    // For the endpoint, see https://api.aliyun.com/product/Dysmsapi
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20170525(config);
  }
}

Node.js example

const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
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'],
    });
    // For the endpoint, see https://api.aliyun.com/product/Dysmsapi
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20170525.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: SendSms.

Note

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

TypeScript example

// Create a request and specify the request parameters.
let sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({
    // Please replace with the recipient's mobile number. 
    phoneNumbers: "<YOUR_VALUE>",
    // Please replace with your SMS signature.
    signName: "<YOUR_VALUE>",
    // Please replace with your SMS template code.
    templateCode: "<YOUR_VALUE>",
});

Node.js example

// Create a request and specify the request parameters.
let sendSmsRequest = new Dysmsapi20170525.SendSmsRequest({
    // Please replace with the recipient's mobile phone number. 
    phoneNumbers: "<YOUR_VALUE>",
    // Please replace with your SMS signature.
    signName: "<YOUR_VALUE>",
    // Please replace with your SMS template code.
    templateCode: "<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.sendSmsWithOptions(sendSmsRequest, runtime);

Node.js example

// Create runtime parameters.
let runtime = new Util.RuntimeOptions({ });
let client = Client.createClient();
// Send a request.
await client.sendSmsWithOptions(sendSmsRequest, 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

SendSms API call example

TypeScript example

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

export default class Client {

  static createClient(): Dysmsapi20170525 {
    let config = new $OpenApi.Config({
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // For the endpoint, see https://api.aliyun.com/product/Dysmsapi.
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20170525(config);
  }

  static async main(): Promise<void> {
    let client = Client.createClient();
    // Create a request and specify the request parameters.
    let sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({
      phoneNumbers: "<YOUR_VALUE>",
      signName: "<YOUR_VALUE>",
      templateCode: "<YOUR_VALUE>",
    });
    let runtime = new $Util.RuntimeOptions({ });
    try {
      // Send the request.
       await client.sendSmsWithOptions(sendSmsRequest, runtime);
    } catch (error) {
      // Handle exceptions with caution in actual business scenarios, and do not ignore exceptions in your project. In this example, exceptions are printed for demonstration.
      // The error message.
      console.log(error.message);
      // The URL for troubleshooting.
      console.log(error.data["Recommend"]);
    }    
  }
}

Client.main();

Node.js example

const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
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.aliyun.com/product/Dysmsapi
    config.endpoint = `dysmsapi.aliyuncs.com`;
    return new Dysmsapi20170525.default(config);
  }

  static async main() {
    let client = Client.createClient();
    // Create a request object and set its parameters.
    let sendSmsRequest = new Dysmsapi20170525.SendSmsRequest({
      phoneNumbers: '<YOUR_VALUE>',
      signName: '<YOUR_VALUE>',
      templateCode: '<YOUR_VALUE>',
    });
    let runtime = new Util.RuntimeOptions({ });
    try {
      // Send the request.
       await client.sendSmsWithOptions(sendSmsRequest, runtime);
    } catch (error) {
      // In this example, exceptions are printed for demonstration purposes. In a real-world business scenario, handle exceptions with caution and do not ignore them.
      // The error message.
      console.log(error.message);
      // The troubleshooting URL.
      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 SendSms or , you can create the following custom permission policy and attach it to the RAM user.

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendSms",
          "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.