Alibaba Cloud SDK for Java V2.0 admite llamadas genéricas a la API, las cuales le permiten invocar cualquier operación de OpenAPI sin instalar los SDK específicos de cada servicio.
Características
Ligero: solo se requiere la biblioteca principal de Alibaba Cloud SDK. No es necesario instalar el SDK de cada servicio.
Fácil de usar: cree parámetros de solicitud comunes y utilice un cliente común para iniciar las solicitudes. Las respuestas se devuelven en formatos comunes.
Para obtener más información, consulte Generic calls and specialized calls.
Notas de uso
Antes de hacer una llamada genérica, consulte los metadata of the API operation para obtener el estilo de la API, los parámetros de solicitud y la URL.
Instalar la biblioteca principal de Alibaba Cloud SDK
Ejecute el siguiente comando para instalar la biblioteca principal de Alibaba Cloud SDK V2.0 para Node.js:
npm install @alicloud/openapi-client
Invocar una operación de la API
Inicializar un cliente de solicitud
Cree el objeto client para inicializar un cliente de solicitud e invocar la operación de la API. También puede usar la herramienta Credentials para gestionar las credenciales. Para obtener más información, consulte Manage access credentials.
// 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)Configurar la información de la operación de la API
Utilice OpenApi.Params para configurar la operación de la API, lo que incluye el estilo, la versión y el método de solicitud. El siguiente ejemplo invoca la operación 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.
});Configurar los parámetros de solicitud
Utilice OpenApi.OpenApiRequest para configurar los parámetros de solicitud. Los parámetros se pueden pasar en una cadena de consulta, un cuerpo o una secuencia. Elija el método según los metadatos de la API. Por ejemplo, el parámetro RegionId de la operación DescribeInstanceTypeFamilies se define como {"name":"RegionId","in":"query",...}} en los metadatos. El valor "in":"query" indica que RegionId se pasa en una cadena de consulta.
|
Forma de pasar el parámetro |
Descripción |
|
query |
Pase el parámetro en la cadena de consulta cuando los metadatos definan |
|
body |
Pase el parámetro en el cuerpo de la solicitud cuando los metadatos definan |
|
stream |
Para cargar archivos, pase secuencias de archivos mediante la configuración del 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.
// });
Iniciar una solicitud
Invoque el método callApi de OpenApiClient para iniciar una solicitud. Puede especificar parámetros de tiempo de ejecución, como los tiempos de espera y la configuración del proxy. Para obtener más información, consulte Advanced settings.
// 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 ejemplo
Invocar una operación de la API de tipo RPC
El siguiente ejemplo hace una llamada genérica a la operación DescribeInstanceTypeFamilies de 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();
Ejemplo: invocar una operación de la API de estilo RESTful (estilo ROA)
El siguiente ejemplo hace una llamada genérica a la operación DescribeClustersV1 de 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();