Install the Node.js SDK

更新时间:
复制 MD 格式

This topic describes how to install and use the Node.js software development kit (SDK), using the Function AI operation GetProject as an example. For more information about the GetProject operation, see GetProject - Query a project.

Prerequisites

  • Create an AccessKey

    An AccessKey pair is required to call Alibaba Cloud OpenAPI. An Alibaba Cloud account has full permissions on all resources. Leaking the AccessKey pair for your Alibaba Cloud account poses a high security risk. We recommend that you use an AccessKey pair from a Resource Access Management (RAM) user that is granted the minimum required permissions.

  • Configure the AccessKey pair in an environment variable

    For more information, see Configure environment variables on Linux, macOS, and Windows.

Environment requirements

Node.js >= 8.x

Install the SDK

Run the following command to install the Function AI SDK:

npm install --save @alicloud/devs20230714

Use the SDK

1. Initialize the client

In the SDK, all OpenAPI calls are made through a client. Before you call an OpenAPI operation, you must initialize the client. The client can be initialized in several ways. This example shows how to initialize the client using an AccessKey pair. For more information about initialization methods, see Manage access credentials.

'use strict';

const Devs20230714 = require('@alicloud/devs20230714');
const OpenApi = require('@alicloud/openapi-client');


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'],
            endpoint: `devs.cn-hangzhou.aliyuncs.com`,
        });
        return new Devs20230714.default(config);
    }
}

2. Build the request object for the operation

When you call an OpenAPI operation, use the request object provided by the SDK to pass parameters. Before you build the request object, see the API reference GetProject - Query a project to obtain parameter information.

Note

The naming convention for request objects is {APIName}Request. For example, the request object for the GetProject operation is GetProjectRequest.

// Build the request object.
client.getProjectWithOptions('my-project', headers, runtime) 

3. Make the call

When you call an OpenAPI operation using the client, you can set runtime parameters, such as timeout and proxy configurations. For more information, see Advanced configuration.

Note

The naming convention for response objects is {APIName}Response. For example, the response object for the GetProject operation is GetProjectResponse.

// Set runtime parameters.
let runtime = new Util.RuntimeOptions({});
// Call the GetProject operation.
await client.getProjectWithOptions('my-project', headers, runtime);

4. Handle exceptions

The V2.0 Node.js SDK classifies exceptions into two main types: UnretryableError and ResponseError.

  • UnretryableError: This exception is thrown after the maximum number of retries is reached, which is usually caused by network issues. You can use err.data.lastRequest to query the information about the request that caused the error.

  • ResponseError: This exception is thrown for business-related errors.

For more information about exception handling, see Exception handling.

Important

You must handle exceptions properly to ensure system robustness and stability. For example, you can propagate exceptions, record logs, or attempt to recover from the error.

5. Complete example

'use strict';

const Devs20230714 = require('@alicloud/devs20230714');
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'],
            endpoint: `devs.cn-hangzhou.aliyuncs.com`,
        });
        return new Devs20230714.default(config);
    }

  static async main(args) {
    let client = Client.createClient();
    let runtime = new Util.RuntimeOptions({ });
    let headers = { };
    try {
      // If you copy the code to run, print the API return value.
      await client.getProjectWithOptions('my-project', headers, runtime);
    } catch (error) {
      // This is for demonstration purposes only. Handle exceptions with care in your projects and do not ignore them.
      // Error message
      console.log(error.message);
      // Diagnosis address
      console.log(error.data["Recommend"]);
      Util.default.assertAsString(error.message);
    }    
  }

}

exports.Client = Client;
Client.main(process.argv.slice(2));

More information

In addition to the method described in this topic, you can also use generalized calls to invoke Function AI OpenAPI operations. For more information, see Generalized calls.