O Alibaba Cloud SDK for Java V2.0 oferece suporte a chamadas de API genéricas, que permitem invocar qualquer operação OpenAPI sem instalar SDKs específicos para cada serviço.
Características
Leveza: requer apenas a biblioteca principal do Alibaba Cloud SDK. Não é necessário instalar o SDK de cada serviço individualmente.
Facilidade de uso: crie parâmetros de solicitação comuns e use um cliente genérico para iniciar as requisições. As respostas retornam em formatos padronizados.
Para mais informações, consulte Chamadas genéricas e chamadas especializadas.
Observações de uso
Antes de fazer uma chamada genérica, visualize os metadados da operação de API para obter o estilo da API, os parâmetros de solicitação e a URL.
Instale a biblioteca principal do Alibaba Cloud SDK
Execute o comando abaixo para instalar a biblioteca principal do Alibaba Cloud SDK V2.0 para Node.js:
npm install @alicloud/openapi-client
Chame uma operação de API
Inicialize um cliente de solicitação
Crie o objeto client para inicializar um cliente de solicitação e chamar a operação de API. Você também pode usar a ferramenta Credentials para gerenciar credenciais. Para mais detalhes, consulte Gerenciar credenciais de acesso.
// Obtain the AccessKey ID and AccessKey secret from environment variables.
let config = new OpenApi.Config({
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
});
config.endpoint = `ecs-cn-hangzhou.aliyuncs.com`;
let client = new OpenApi.default(config);
// If you do not specify parameters, the default credential chain is used.
// const credentialClient = new Credential.default();
// let config = new OpenApi.Config({
// credential: credentialClient,
// });
// config.endpoint = `ecs-cn-hangzhou.aliyuncs.com`;
// let client = new OpenApi.default(config);
// Obtain the AccessKey ID and AccessKey secret from environment variables.
let config = new $OpenApi.Config({
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
});
config.endpoint = `ecs-cn-hangzhou.aliyuncs.com`;
let client = new OpenApi(config);
// If you do not specify parameters, the default credential chain is used.
// let credential = new Credential();
// let config = new $OpenApi.Config({
// credential: credential,
// });
// config.endpoint = `ecs.cn-hangzhou.aliyuncs.com`;
// let client = new OpenApi(config)
Configure as informações da operação de API
Use OpenApi.Params para configurar a operação de API, incluindo estilo, versão e método de solicitação. O exemplo a seguir chama a operação DescribeInstanceTypeFamilies.
// Configure the information about the API operation.
let params = new OpenApi.Params({
style: 'RPC', // The API style, such as remote procedure call (RPC) and resource-oriented architecture (ROA).
action: 'DescribeInstanceTypeFamilies', // The API operation.
version: '2014-05-26', // The version number of the API operation.
protocol: 'HTTPS', // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
method: 'POST', // The HTTP method of the API operation.
authType: 'AK', // The authentication type. Use the default type. If the operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request.
pathname: `/`, // The URL of the operation. The default path of an RPC-style operation is /. You can obtain the URL of an ROA-style operation from the data.path parameter in the API metadata.
reqBodyType: 'json', // The format of the request body.
bodyType: 'json', // The format of the response body.
});
// Configure the information about the API operation.
let params = new $OpenApi.Params({
style: 'RPC', // The API style, such as remote procedure call (RPC) and resource-oriented architecture (ROA).
action: 'DescribeInstanceTypeFamilies', // The API operation.
version: '2014-05-26', // The version number of the API operation.
protocol: 'HTTPS', // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
method: 'POST', // The HTTP method of the API operation.
authType: 'AK', // The authentication type. Use the default type. If the operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request.
pathname: `/`, // The URL of the operation. The default path of an RPC-style operation is /. You can obtain the URL of an ROA-style operation from the data.path parameter in the API metadata.
reqBodyType: 'json', // The format of the request body.
bodyType: 'json', // The format of the response body.
});
Configure os parâmetros de solicitação
Use OpenApi.OpenApiRequest para definir os parâmetros de solicitação. É possível enviar parâmetros via query string, body ou stream. Escolha o método com base nos metadados da API. Por exemplo, o parâmetro RegionId da operação DescribeInstanceTypeFamilies está definido como {"name":"RegionId","in":"query",...}} nos metadados. A definição "in":"query" indica que RegionId deve ser passado na query string.
|
Forma de envio do parâmetro |
Descrição |
|
query |
Envie o parâmetro na query string quando os metadados definirem |
|
body |
Inclua o parâmetro no corpo da solicitação se os metadados especificarem |
|
stream |
Para upload de arquivos, transmita fluxos de arquivo configurando o parâmetro Stream. |
// Scenario 1: Configure the query string
let query = { 'RegionId': 'cn-hangzhou' };
let request = new OpenApi.OpenApiRequest({
query: OpenApiUtil.default.query(query),
});
// Scenario 2: Configure the body and set reqBodyType to json.
// let body = {
// 'param1': 'value1',
// 'param2': 'value2',
// };
// let request = new OpenApi.OpenApiRequest({
// body: OpenApiUtil.default.query(body),
// });
// Scenario 3: Configure the Stream parameter to pass file streams
// let request = new OpenApi.OpenApiRequest({
// stream: '<FILE_STREAM>', // Replace <FILE_STREAM> with the actual file stream.
// });
// Scenario 4: Configure a request body and set reqBodyType to formData.
// let formParams = {
// 'param1': 'value1',
// 'param2': 'value2',
// };
// let request = new OpenApi.OpenApiRequest({
// body: formParams,
// });
// Scenario 1: Configure the query string
let query: { [key: string]: any } = { "RegionId": "cn-hangzhou" };
let request = new $OpenApi.OpenApiRequest({
query: OpenApiUtil.query(query),
});
// Scenario 2: Configure the body and set reqBodyType to json.
// let body = {
// "param1": "value1",
// "param2": "value2",
// };
// let request = new $OpenApi.OpenApiRequest({
// body: OpenApiUtil.query(body),
// });
// Scenario 3: Configure the Stream parameter to pass file streams
// let request = new $OpenApi.OpenApiRequest({
// stream: '<FILE_STREAM>', // Replace <FILE_STREAM> with the actual file stream.
// });
// Scenario 4: Configure a request body and set reqBodyType to formData.
// let formParams = {
// "param1": "value1",
// "param2": "value2",
// };
// let request = new $OpenApi.OpenApiRequest({
// body: formParams, // Directly pass form parameters.
// });
Inicie uma solicitação
Invoque o método callApi de OpenApiClient para enviar a requisição. É possível especificar parâmetros de tempo de execução, como timeout e configurações de proxy. Para mais informações, consulte Configurações avançadas.
// Configure the runtime parameters.
let runtime = new Util.RuntimeOptions({
// A value of true specifies to disable certificate verification. A value of false specifies to enable certificate verification.
// ignoreSSL: true,
// Configure an HTTP proxy.
// httpProxy: "http://xx.xx.xx.xx:xxxx",
// httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
// Configure the addresses that do not require proxies.
// noProxy: '127.0.0.1,localhost',
// Configure a timeout period for connection requests.
// connectTimeout: 10000,
// Configure a timeout period for read requests.
// readTimeout: 10000
});
// Send the request.
let response = await client.callApi(params, request, runtime);
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
console.log(JSON.stringify(response.body))
// Configure the runtime parameters.
let runtime = new $Util.RuntimeOptions({
// A value of true specifies to disable certificate verification. A value of false specifies to enable certificate verification.
// ignoreSSL: true,
// Configure an HTTP proxy.
// httpProxy: "http://xx.xx.xx.xx:xxxx",
// httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
// Configure the addresses that do not require proxies.
// noProxy: '127.0.0.1,localhost',
// Configure a timeout period for connection requests.
// connectTimeout: 10000,
// Configure a timeout period for read requests.
// readTimeout: 10000
});
// Send the request.
let response = await client.callApi(params, request, runtime);
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
console.log(JSON.stringify(response.body));
Código de exemplo
Chamar uma operação de API RPC
O exemplo abaixo faz uma chamada genérica para a operação DescribeInstanceTypeFamilies do ECS.
Node.js
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const OpenApiUtil = require('@alicloud/openapi-util');
class Client {
static async main() {
// Obtain the AccessKey ID and AccessKey secret from environment variables.
let config = new OpenApi.Config({
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
});
config.endpoint = `ecs-cn-hangzhou.aliyuncs.com`;
let client = new OpenApi.default(config);
let params = new OpenApi.Params({
style: 'RPC', // The API style.
action: 'DescribeInstanceTypeFamilies', // The API operation.
version: '2014-05-26', // The version number of the operation.
protocol: 'HTTPS', // The protocol of the operation.
method: 'POST', // The HTTP method of the operation.
authType: 'AK', // The authentication type. Use the default type. If the operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request.
pathname: `/`, // The URL of the operation. The default path of an RPC-style operation is /. You can obtain the URL of an ROA-style operation from the data.path parameter in the API metadata.
reqBodyType: 'json', // The format of the request body.
bodyType: 'json', // The format of the response body.
});
let query = { 'RegionId': 'cn-hangzhou' };
let request = new OpenApi.OpenApiRequest({
query: OpenApiUtil.default.query(query),
});
let runtime = new Util.RuntimeOptions({});
let response = await client.callApi(params, request, runtime);
console.log(JSON.stringify(response.body, null, 2))
}
}
exports.Client = Client;
Client.main();
TypeScript
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
import OpenApiUtil from '@alicloud/openapi-util';
export default class Client {
static async main(): Promise<void> {
// Obtain the AccessKey ID and AccessKey secret from environment variables.
let config = new $OpenApi.Config({
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
});
config.endpoint = `ecs-cn-hangzhou.aliyuncs.com`;
let client = new OpenApi(config);
let params = new $OpenApi.Params({
style: 'RPC', // The API style.
action: 'DescribeInstanceTypeFamilies', // The API operation.
version: '2014-05-26', // The version number of the operation.
protocol: 'HTTPS', // The protocol of the operation.
method: 'POST', // The HTTP method of the operation.
authType: 'AK',
pathname: `/`, // The URL of the operation.
reqBodyType: 'json', // The format of the request body.
bodyType: 'json', // The format of the response body.
});
// Configure the query string.
let query: { [key: string]: any } = { "RegionId": "cn-hangzhou" };
// Create an API request.
let request = new $OpenApi.OpenApiRequest({
query: OpenApiUtil.query(query),
});
// Configure the runtime parameters.
let runtime = new $Util.RuntimeOptions({});
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
let response = await client.callApi(params, request, runtime);
console.log(JSON.stringify(response.body));
}
}
Client.main();
Exemplo: Chamar uma operação de API estilo RESTful (ROA)
Este exemplo demonstra uma chamada genérica para a operação DescribeClustersV1 do ACK.
Node.js
const OpenApi = require('@alicloud/openapi-client');
const OpenApiUtil = require('@alicloud/openapi-util');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');
class Client {
static async main() {
// Obtain the AccessKey ID and AccessKey secret from environment variables.
let config = new OpenApi.Config({
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
});
config.endpoint = `cs.cn-qingdao.aliyuncs.com`;
let client = new OpenApi.default(config);
let params = new OpenApi.Params({
// The operation that you want to call.
action: 'DescribeClustersV1',
// The version number of the API operation.
version: '2015-12-15',
// The protocol over which the operation is called.
protocol: 'HTTPS',
// The HTTP method of the API operation.
method: 'GET',
// The authentication type. Use the default type. If the operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request.
authType: 'AK',
style: 'ROA',
// The URL of the operation. The default path of an RPC-style operation is /. You can obtain the URL of an ROA-style operation from the data.path parameter in the API metadata.
pathname: `/api/v1/clusters`,
// The format of the request body.
reqBodyType: 'json',
// The format of the response body.
bodyType: 'json',
});
// query params
let queries = {};
queries['name'] = 'cluster-demo';
let request = new OpenApi.OpenApiRequest({
query: OpenApiUtil.default.query(queries),
});
// runtime options
let runtime = new Util.RuntimeOptions({});
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
let response = await client.callApi(params, request, runtime);
console.log(response.body);
}
}
exports.Client = Client;
Client.main();
TypeScript
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import OpenApiUtil from '@alicloud/openapi-util';
import Util, * as $Util from '@alicloud/tea-util';
import * as $tea from '@alicloud/tea-typescript';
export default class Client {
static async main(): Promise<void> {
let config = new $OpenApi.Config({
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
});
config.endpoint = `cs.cn-qingdao.aliyuncs.com`;
let client = new OpenApi(config);
let params = new $OpenApi.Params({
// The operation that you want to call.
action: "DescribeClustersV1",
// The version number of the API operation.
version: "2015-12-15",
// The protocol over which the operation is called.
protocol: "HTTPS",
// The HTTP method of the API operation.
method: "GET",
authType: "AK",
style: "ROA",
// The URL of the operation.
pathname: `/api/v1/clusters`,
// The format of the request body.
reqBodyType: "json",
// The format of the response body.
bodyType: "json",
});
// query params
let queries: { [key: string]: any } = { "name": "cluster-demo" };
let request = new $OpenApi.OpenApiRequest({
query: OpenApiUtil.query(queries),
});
// runtime options
let runtime = new $Util.RuntimeOptions({});
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
let response = await client.callApi(params, request, runtime);
console.log(JSON.stringify(response.body));
}
}
Client.main();