Todos os produtos
Search
Central de documentação

Alibaba Cloud SDK:Integrar o SDK

Última atualização: Jun 28, 2026

Integre o SDK do Alibaba Cloud ao seu projeto para simplificar chamadas à OpenAPI, acelerar a integração de recursos e reduzir custos de manutenção. Este tópico aborda a instalação e o uso básico do SDK.

Pré-requisitos

Node.js 8.x ou superior

Instale o SDK

O SDK V1.0 para Node.js suporta apenas chamadas generalizadas (CommonRequest), que exigem somente a dependência @alicloud/pop-core. Execute o comando a seguir para instalá-la:

npm install @alicloud/pop-core

Usar o SDK

O SDK V1.0 para Node.js oferece dois estilos de chamada: RPC e ROA. Os exemplos a seguir utilizam a operação DescribeInstances do ECS para RPC e a operação DescribeClustersV1 do Container Service for Kubernetes (ACK) para ROA.

1. Inicializar o cliente de requisição

Todas as operações da OpenAPI são invocadas por meio do RPCClient ou ROAClient fornecidos pelo @alicloud/pop-core. Inicialize o cliente antes de chamar qualquer operação. O exemplo a seguir utiliza um par de AccessKey. Para outros métodos de inicialização, consulte Inicializar o cliente usando um token STS.

Nota

O exemplo obtém credenciais de variáveis de ambiente. Antes de executar o código, configure as variáveis de ambiente ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET. Para mais informações, consulte Configurar variáveis de ambiente em sistemas Linux, macOS e Windows.

Cliente RPC

// Initialize the RPC client
const Core = require('@alicloud/pop-core');
var client = new Core({
  // 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 domain name in the http(s)://<product_endpoint> format. We recommend that you use HTTPS. Example for ECS: http://ecs-cn-hangzhou.aliyuncs.com
  endpoint: 'https://ecs.cn-hangzhou.aliyuncs.com',
  // The API version of the cloud product. Example for ECS: 2014-05-26
  apiVersion: '2014-05-26'
});

Cliente ROA

// Initialize the ROA client
var ROAClient = require('@alicloud/pop-core').ROAClient;
var client = new ROAClient({
  // 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 domain name in the http(s)://<product_endpoint> format. We recommend that you use HTTPS. Example for Container Service: http://cs.cn-chengdu.aliyuncs.com
  endpoint: 'https://cs.cn-chengdu.aliyuncs.com',
  // The API version of the cloud product. Example for Container Service: 2015-12-15
  apiVersion: '2015-12-15'
});

2. Construir os parâmetros da requisição

Uma requisição exige três parâmetros: o nome da operação da OpenAPI, o objeto de parâmetros da requisição e o objeto de parâmetros de runtime.

Nota

Não há suporte para upload de arquivos locais. Para fazer upload de um arquivo local, utilize o SDK V2.0.

Parâmetros de chamada RPC

// The name of the OpenAPI operation
var action = 'DescribeInstances'
// The request parameters
var params = {
  "RegionId": "cn-hangzhou",
  "InstanceIds": "[\"i-bp67************\", \"i-7xva************\", … \"i-7xvc************\"]"
}
// The runtime parameters
var requestOption = {
  method: 'POST',
  formatParams: false,
};

Parâmetros de chamada ROA

// The request method
const method = "GET"
// The path parameter
const uriPattern = '/api/v1/clusters';
// The query parameters
var queryParams = {
  "cluster_type": "Kubernetes",
  "name": "cluster-demo"
};
// The request body in the JSON string format. Example: `{"nodepool_info":{"name":"nodepool-test","type":"ess"}}`;
const body = "";
// The custom request headers
const headers = {
  "Content-Type": "application/json"
};
// The runtime parameters
const options = {
  timeout: 3000, // default 3000 ms
};

3. Enviar a requisição

Chame a operação request do cliente criado na Etapa 1 e passe os parâmetros construídos na Etapa 2.

Chamada RPC

// Send the request
client.request(action, params, requestOption).then((result) => {
  console.log(JSON.stringify(result));
}, (ex) => {
  console.log(ex);
})

Chamada ROA

// Send the request
roaClient.request(method, uriPattern, queryParams, body, headers, options)
  .then((response) => {
    console.log('ROA Response:', response);
  })
  .catch((error) => {
    console.error('ROA Error:', error);
  });

4. Tratar exceções

Por padrão, o sistema lança uma exceção se o campo Code na resposta da API não for 200, OK, Success ou success. Defina códigos de erro personalizados para seu programa conforme necessário. Para mais informações, consulte Tratamento de exceções.

Exemplos completos de código

Chamada RPC

// Initialize the RPC client
const Core = require('@alicloud/pop-core');

var client = new Core({
  // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  // The domain name in the http(s)://<product_endpoint> format. We recommend that you use HTTPS. Example for ECS: http://ecs-cn-hangzhou.aliyuncs.com
  endpoint: 'https://ecs.cn-hangzhou.aliyuncs.com',
  // The API version of the cloud product. Example for ECS: 2014-05-26
  apiVersion: '2014-05-26'
});

// The name of the OpenAPI operation
var action = 'DescribeInstances'

// The request parameters
var params = {
  "RegionId": "cn-hangzhou",
  "InstanceIds": "[\"i-bp67acfmxazb4p****\", \"i-bp67acfmxazb4p****\", … \"i-bp67acfmxazb4p****\"]"
}

// The runtime parameters
var requestOption = {
  method: 'POST',
  formatParams: false,
};

// Send the request
client.request(action, params, requestOption).then((result) => {
  console.log(JSON.stringify(result));
}, (ex) => {
  console.log(ex);
})

Chamada ROA

const ROAClient = require('@alicloud/pop-core').ROAClient;

// Initialize the ROA client
var ROAClient = require('@alicloud/pop-core').ROAClient;
var client = new ROAClient({
  // 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 domain name in the http(s)://<product_endpoint> format. We recommend that you use HTTPS. Example for Container Service: http://cs.cn-chengdu.aliyuncs.com
  endpoint: 'https://cs.cn-chengdu.aliyuncs.com',
  // The API version of the cloud product. Example for Container Service: 2015-12-15
  apiVersion: '2015-12-15'
});

// The request method
const method = "GET"
// The path parameter
const uriPattern = '/api/v1/clusters';
// The query parameters
var queryParams = {
  "cluster_type": "Kubernetes",
  "name": "cluster-demo"
};
// The request body in the JSON string format. Example: `{"nodepool_info":{"name":"nodepool-test","type":"ess"}}`;
const body = "";
// The custom request headers
const headers = {
  "Content-Type": "application/json"
};
// The runtime parameters
const options = {
  timeout: 3000, // default 3000 ms
};

// Send the request
roaClient.request(method, uriPattern, queryParams, body, headers, options)
  .then((response) => {
    console.log('ROA Response:', response);
  })
  .catch((error) => {
    console.error('ROA Error:', error);
  });

Referências