Alibaba Cloud SDK for Java V2.0 prend en charge les appels d'API génériques, qui permettent d'appeler n'importe quelle opération OpenAPI sans installer les SDK spécifiques à chaque service.
Caractéristiques
Légèreté : seule la bibliothèque principale d'Alibaba Cloud SDK est requise. Vous n'avez pas besoin d'installer le SDK de chaque service.
Simplicité d'utilisation : créez des paramètres de requête communs et utilisez un client commun pour envoyer les requêtes. Les réponses sont renvoyées dans des formats standardisés.
Pour plus d'informations, consultez la rubrique Appels génériques et appels spécialisés.
Remarques sur l'utilisation
Avant d'effectuer un appel générique, consultez les métadonnées de l'opération API pour obtenir le style de l'API, les paramètres de requête et l'URL.
Installer la bibliothèque principale d'Alibaba Cloud SDK
Exécutez la commande suivante pour installer la bibliothèque principale d'Alibaba Cloud SDK V2.0 pour Node.js :
npm install @alicloud/openapi-client
Appeler une opération API
Initialiser un client de requête
Créez l'objet client pour initialiser un client de requête et appeler l'opération API. Vous pouvez également utiliser l'outil Credentials pour gérer les identifiants. Pour plus d'informations, consultez la rubrique Gérer les identifiants d'accès.
// 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)Configurer les informations de l'opération API
Utilisez OpenApi.Params pour configurer l'opération API, notamment son style, sa version et sa méthode de requête. L'exemple suivant appelle l'opération 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.
});Configurer les paramètres de requête
Utilisez OpenApi.OpenApiRequest pour définir les paramètres de requête. Ces paramètres peuvent être transmis via une chaîne de requête (query string), un corps de requête ou un flux. Choisissez la méthode appropriée selon les métadonnées de l'API. Par exemple, le paramètre RegionId de l'opération DescribeInstanceTypeFamilies est défini par {"name":"RegionId","in":"query",...}} dans les métadonnées. La mention "in":"query" indique que RegionId est passé dans une chaîne de requête.
|
Mode de transmission du paramètre |
Description |
|
query |
Transmettez le paramètre dans la chaîne de requête lorsque les métadonnées indiquent |
|
body |
Placez le paramètre dans le corps de la requête si les métadonnées spécifient |
|
stream |
Pour uploader des fichiers, transmettez des flux de fichiers en configurant le paramètre 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.
// });
Envoyer une requête
Appelez la méthode callApi de OpenApiClient pour envoyer une requête. Vous pouvez spécifier des paramètres d'exécution tels que le délai d'expiration et les paramètres de proxy. Pour plus d'informations, consultez la rubrique Paramètres avancés.
// 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)); Exemples de code
Appeler une opération API RPC
L'exemple ci-dessous effectue un appel générique à l'opération ECS DescribeInstanceTypeFamilies.
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();
Exemple : Appeler une opération API de style RESTful (ROA)
L'exemple suivant effectue un appel générique à l'opération ACK DescribeClustersV1.
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();