Integrate the SDK
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
-
Log on to SDK Center and select the product for the API you want to call, such as Short Message Service (SMS).
-
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).

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
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=yourAccessKeyIDConfigure the AccessKey secret and press Enter.
# Replace yourAccessKeySecret with your AccessKey secret. export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecretVerify the configuration.
Run the
echo $ALIBABA_CLOUD_ACCESS_KEY_IDcommand. 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%andecho %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 /MThe
/Mparameter 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%andecho %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.
-
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.
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.
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.
Always handle exceptions — propagate, log, or recover. Never silently ignore them.
Click to view the complete code example
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.
Temporary files stored in Alibaba Cloud OSS are cleared periodically.
-
Initialize the request client
Set both
regionIdandendpointto the same region. TheregionIddetermines where the temporary OSS file is stored. If you omitregionId, 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); } -
Create the request object
Create a
<OpenAPIName>AdvanceRequestobject to pass the file stream. The parameter name for the file stream isImageURLObject.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, }); -
Send the request
Call the
<operationName>Advancefunction 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);
FAQ
-
"You are not authorized to perform this operation" error when calling an API
-
"triggerUncaughtException Error: getaddrinfo ENOTFOUND" error (endpoint issue)
-
"Cannot read properties of undefined (reading 'getCredential')" or "InvalidAccessKeyId.NotFound: code: 404" error
For other common errors, see FAQ.