All Products
Search
Document Center

Alibaba Cloud SDK:Generic calls

Last Updated:May 13, 2025

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 Go 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 V2.0 for Go

Run the following command on your terminal to install the core library of Alibaba Cloud SDK V2.0 for Go:

go get github.com/alibabacloud-go/darabonba-openapi/v2/client

Call an API operation

Initialize a request client

Create the darabonba-openapi/v2/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.

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 basic information about the API operation, such as the API style, API version, and request method. In the following example, the DescribeInstanceTypeFamilies operation is called.

        // 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 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 "in":"query", pass the parameter in the query string.

Body

If the metadata defines "in":"body'' or "in": "formData", pass the parameter in the request body. If you pass request parameters in the request body, specify a value for the reqBodyType parameter based on the request body type.

Stream

If you need to upload files, you can 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

Use the client to initiate a request by calling the CallApi function. 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 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

In this example, the DescribeRegions operation of ECS is called to show how to make a generic call of an 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

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.

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"])
}