Alibaba Cloud SDK for Java V2.0 supports generic API calls. This topic describes how to make generic calls by using Alibaba Cloud SDK for Java V2.0.
Characteristic
Lightweight: You can use Alibaba Cloud SDK V2.0 for Node.js to call API operations by installing only the core library of Alibaba Cloud SDK, without the need to install the SDK of each service.
Easy to use: You only need to create common request parameters and use a common client to initiate requests. The responses are returned in common formats.
For more information, see Generic calls and specialized calls.
Usage notes
Before you make a generic call, we recommend that you view the metadata of the API operation to obtain the API style, request parameters, and URL.
Install the core library of Alibaba Cloud SDK
Run the following command on your terminal to install the core library of Alibaba Cloud SDK V2.0 for Node.js:
npm install @alicloud/openapi-clientCall an API operation
Initialize a request client
Create the client object to initialize a request client, and use the client to call the API operation. When you initialize a client, you can also use the Credentials tool. For more information about the Credentials tool, see 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)Configure the information about the API operation
Use OpenApi.Params to configure the basic information about the API operation that you want to call, such as the API style, API version, and request method. In the following example, the DescribeInstanceTypeFamilies operation is called.
// 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 request parameters
Use OpenApi.OpenApiRequest to configure the request parameters. You can pass the request parameters in a query string, a body, or a stream. Select a method to pass request parameters based on the metadata of the API operation. For example, the RegionId request parameter of the DescribeInstanceTypeFamilies API operation is defined as {"name":"RegionId","in":"query",...}} in the metadata. "in":"query" indicates that the RegionId parameter is passed in a query string.
How the parameter is passed | Description |
query | If the metadata defines |
body | If the metadata defines |
stream | If you need to upload files, you can pass file streams by configuring the Stream parameter. |
// 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.
// });
Initiate a request
Use OpenApiClient to call the callApi method to initiate a request. When you call an API operation, you can specify runtime parameters, such as timeout parameters and proxy parameters. For more information, see 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)); Sample code
Call an RPC API operation
In this example, the DescribeRegions operation of ECS is called to show how to make a generic call of an operation.
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();Example: Call a RESTful-style (ROA-style) API operation
In this example, the DescribeClustersV1 operation of Container Service for Kubernetes (ACK) is called to show how to make a generic call of an operation.
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();