Alibaba Cloud SDK for Java V2.0 supports generic API calls, which allow you to call any OpenAPI operation without installing service-specific SDKs.
Characteristic
Lightweight: Only the core library of Alibaba Cloud SDK is required. You do not need to install the SDK of each service.
Easy to use: Construct a common request parameter object, use a common client to send the request, and receive responses in a common format.
For more information, see Generic calls and specialized calls.
Usage notes
Before you make a generic call, view the metadata of the API operation to obtain the API style, request parameters, and URL.
Install the core library of Alibaba Cloud SDK V2.0 for Go
Run the following command to install the core library:
go get github.com/alibabacloud-go/darabonba-openapi/v2/client
Call an API operation
Initialize a request client
Create a darabonba-openapi/v2/client object to initialize the request client. You can also use the Credentials tool to initialize the client. For more information, see Manage access credentials.
import (
"fmt"
"os"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
"github.com/alibabacloud-go/tea/tea"
"github.com/aliyun/credentials-go/credentials"
)
// os.Getenv indicates that the AccessKey ID and AccessKey secret are obtained from environment variables.
config := &openapi.Config{
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
// Specify the endpoint of the service.
config.Endpoint = tea.String("ecs-cn-hangzhou.aliyuncs.com")
// Initialize and return the client.
client, err := openapi.NewClient(config)
if err != nil {
panic(err)
}
// Use the default credential to initialize the client.
// credentialClient, _err := credentials.NewCredential(nil)
// if _err != nil {
// panic(_err)
// }
// config := &openapi.Config{
// Credential: credentialClient,
// }
// config.Endpoint = tea.String("ecs-cn-hangzhou.aliyuncs.com")
// client, err := openapi.NewClient(config)
// if err != nil {
// panic(_err)
// }
Configure the information about the API operation
Use openapi.Params to configure the API operation, including the API style, version, and request method. The following example calls the DescribeInstanceTypeFamilies operation.
// Configure the basic information about the API operation.
params := &openapi.Params{
// Specify the required parameters such as Action and Version for the API operation.
Action: tea.String("DescribeInstanceTypeFamilies"), // The API operation.
Version: tea.String("2014-05-26"), // The version number of the API operation.
Protocol: tea.String("HTTPS"), // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
Method: tea.String("POST"), // The request method.
AuthType: tea.String("AK"), // The authentication type. Use the default type. If the API operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request.
Style: tea.String("RPC"), // The API style, such as remote procedure call (RPC) and resource-oriented architecture (ROA).
Pathname: tea.String("/"), // The URL of the API 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: tea.String("json"), // The type of request body. Valid values: byte, json, and formData.
BodyType: tea.String("json"), // The response format. Valid value: json.
}
Configure request parameters
Use openapi.OpenApiRequest to configure request parameters. Parameters can be passed in a query string, a request body, or a stream. Choose the method based on the API metadata. For example, the RegionId parameter of the DescribeInstanceTypeFamilies operation is defined as {"name":"RegionId","in":"query",...}} in the metadata. "in":"query" indicates that RegionId is passed in a query string.
|
How the parameter is passed |
Description |
|
Query |
If the metadata defines |
|
Body |
If the metadata defines |
|
Stream |
To upload files, pass file streams by configuring the Stream parameter. |
// Scenario 1: Configure a query string.
query := map[string]interface{}{
"RegionId": tea.String("cn-hangzhou"),
}
// Create a request and configure the required parameters.
request := &openapi.OpenApiRequest{
Query: openapiutil.Query(query),
}
// Scenario 2: Configure a body and set reqBodyType to json.
// reqBody := map[string]interface{}{
// "param1": tea.String("value1"),
// "param2": tea.String("value2"),
// }
// // Create an API request and set the required parameters.
// request := &openapi.OpenApiRequest{
// Body: openapiutil.Query(reqBody),
// }
// Scenario 3: Configure a body and set reqBodyType to formData.
// reqForm := map[string]interface{}{
// "param1": tea.String("value1"),
// "param2": tea.String("value2"),
// }
// request := &openapi.OpenApiRequest{
// // Convert the form parameters to a URL-encoded string.
// Body: reqForm,
// }
// Scenario 4: Use the Stream parameter to pass file streams
// request := &openapi.OpenApiRequest{
// Stream: '<FILE_STREAM>', // Replace <FILE_STREAM> with the file stream that you want to pass.
// }
Initiate a request
Call the CallApi function on the client to send the request. You can specify runtime parameters such as timeouts and proxies. For more information, see Advanced settings.
// Configure runtime options.
runtime := &util.RuntimeOptions{}
// Ignore SSL certificate-related errors.
// runtime.IgnoreSSL = tea.Bool(true)
// Configure a proxy by using RuntimeOptions.
// runtime.HttpProxy = tea.String("http://127.0.0.1:9898")
// runtime.HttpsProxy = tea.String("http://user:password@127.0.0.1:8989")
// runtime.NoProxy = tea.String("127.0.0.1,localhost")
// Configure timeout periods. Unit: milliseconds.
// runtime.ConnectTimeout = tea.Int(10000) // Set the timeout period for connection requests to 10 seconds.
// runtime.ReadTimeout = tea.Int(10000) // Set the timeout period for read requests to 10 seconds.
// Call the API operation and return the response.
response, err := client.CallApi(params, request, runtime)
if err != nil {
panic(err)
}
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
fmt.Println(response["body"])
Sample code
Example: Call an RPC-style API operation
The following example makes a generic call to the ECS DescribeInstanceTypeFamilies operation.
package main
import (
"fmt"
"os"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
openapiutil "github.com/alibabacloud-go/openapi-util/service"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
func main() {
// Obtain the AccessKey ID and AccessKey secret from environment variables.
config := &openapi.Config{
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
// Specify the endpoint of the service.
config.Endpoint = tea.String("ecs-cn-hangzhou.aliyuncs.com")
// Initialize and return the client.
client, err := openapi.NewClient(config)
if err != nil {
panic(err)
}
params := &openapi.Params{
// Specify the required parameters such as Action and Version for the API operation.
Action: tea.String("DescribeInstanceTypeFamilies"), // The API operation.
Version: tea.String("2014-05-26"), // The version number of the API operation.
Protocol: tea.String("HTTPS"), // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
Method: tea.String("POST"), // The request method.
AuthType: tea.String("AK"), // The authentication type. Use the default type. If the API operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request.
Style: tea.String("RPC"), // The API style, such as RPC and ROA.
Pathname: tea.String("/"), // The path of the API operation. The default path of RPC-style API operations is /.
ReqBodyType: tea.String("json"), // The format of the request body.
BodyType: tea.String("json"), // The format of the response body.
}
// Configure the query parameters.
query := map[string]interface{}{
"RegionId": tea.String("cn-hangzhou"),
}
// Configure the runtime options.
runtime := &util.RuntimeOptions{}
// Create an API request and configure the parameters.
request := &openapi.OpenApiRequest{
Query: openapiutil.Query(query),
}
// Call the API operation and return the response.
response, err := client.CallApi(params, request, runtime)
if err != nil {
panic(err)
}
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
fmt.Println(response["body"])
}
Example: Call a RESTful-style (ROA-style) API operation
The following example makes a generic call to the ACK DescribeClustersV1 operation.
package main
import (
"fmt"
"os"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
openapiutil "github.com/alibabacloud-go/openapi-util/service"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
func main() {
// Obtain the AccessKey ID and AccessKey secret from environment variables.
config := &openapi.Config{
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
// Specify the endpoint of the service. For more information, visit https://api.aliyun.com/product/CS.
config.Endpoint = tea.String("cs.cn-qingdao.aliyuncs.com")
client, err := openapi.NewClient(config)
if err != nil {
panic(err)
}
params := &openapi.Params{
// The operation that you want to call.
Action: tea.String("DescribeClustersV1"),
// The version number of the API operation.
Version: tea.String("2015-12-15"),
// The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
Protocol: tea.String("HTTPS"),
// The HTTP method of the API operation.
Method: tea.String("GET"),
// The authentication type. Use the default type. If the API operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request.
AuthType: tea.String("AK"),
// API style, such as RPC and ROA.
Style: tea.String("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: tea.String("/api/v1/clusters"),
// The format of the request body.
ReqBodyType: tea.String("json"),
// The format of the response body.
BodyType: tea.String("json"),
}
// Configure the query parameters.
queries := map[string]interface{}{}
queries["name"] = tea.String("cluster-demo")
request := &openapi.OpenApiRequest{
Query: openapiutil.Query(queries),
}
// runtime options
runtime := &util.RuntimeOptions{}
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
response, err := client.CallApi(params, request, runtime)
if err != nil {
panic(err)
}
fmt.Println(response["body"])
}