Tous les produits
Search
Centre de documentation

Alibaba Cloud SDK:Appels génériques

Dernière mise à jour :Aug 11, 2026

Alibaba Cloud SDK for Java V2.0 prend en charge les appels d'API génériques. Cette fonctionnalité permet d'appeler n'importe quelle opération OpenAPI sans installer les SDK spécifiques à chaque service.

Caractéristiques

Léger : seule la bibliothèque principale d'Alibaba Cloud SDK est requise. L'installation du SDK de chaque service n'est pas nécessaire.

Simple d'utilisation : construisez un objet de paramètres de requête commun, utilisez un client standard pour envoyer la requête et recevez les réponses dans un format commun.

Pour plus d'informations, consultez Appels génériques et appels spécialisés.

Remarques d'utilisation

Avant d'effectuer un appel générique, consultez les métadonnées de l'opération API afin d'obtenir le style de l'API, les paramètres de requête et l'URL.

Installer la bibliothèque principale d'Alibaba Cloud SDK V2.0 for Go

Exécutez la commande suivante pour installer la bibliothèque principale :

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

Appeler une opération API

Initialiser un client de requête

Créez un objet darabonba-openapi/v2/client pour initialiser le client de requête. Vous pouvez également utiliser l'outil Credentials pour initialiser le client. Pour plus d'informations, consultez Gérer les identifiants d'accès.

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)
	// }

Configurer les informations de l'opération API

Utilisez openapi.Params pour configurer l'opération API, y compris le style de l'API, la version et la méthode de requête. L'exemple suivant appelle l'opération DescribeInstanceTypeFamilies.

        // 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. 
	}

Configurer les paramètres de requête

Utilisez openapi.OpenApiRequest pour configurer les paramètres de requête. Les paramètres peuvent être transmis via une chaîne de requête, 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 comme {"name":"RegionId","in":"query",...}} dans les métadonnées. La valeur "in":"query" indique que RegionId est transmis dans une chaîne de requête.

Mode de transmission du paramètre

Description

Query

Si les métadonnées définissent "in":"query", transmettez le paramètre dans une chaîne de requête.

Body

Lorsque les métadonnées spécifient "in":"body'' ou "in": "formData", transmettez le paramètre dans le corps de la requête. Si vous transmettez des paramètres de requête dans le corps de la requête, spécifiez une valeur pour le paramètre reqBodyType en fonction du type de corps de requête.

Stream

Pour télécharger des fichiers, transmettez des flux de fichiers en configurant le paramètre Stream.

        // 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.
	// }

Envoyer une requête

Appelez la fonction CallApi sur le client pour envoyer la requête. Vous pouvez spécifier des paramètres d'exécution tels que les délais d'attente et les proxys. Pour plus d'informations, consultez Paramètres avancés.

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

Exemples de code

Exemple : Appeler une opération API de style RPC

L'exemple suivant effectue un appel générique à l'opération ECS DescribeInstanceTypeFamilies.

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

Exemple : Appeler une opération API de style RESTful (ROA)

L'exemple suivant effectue un appel générique à l'opération ACK DescribeClustersV1.

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