泛化调用

更新时间:

阿里云SDK支持一种通用的方式调用OpenAPI,此方式被称为泛化调用。本文将为您详细介绍如何使用泛化调用访问OpenAPI。

特点

轻量:仅需安装阿里云核心SDK,无需额外安装云产品SDK。

简单:只需构造通用的请求参数对象,然后利用通用请求客户端调用通用函数发起请求,调用结果也以通用格式返回。

更多介绍,请参见泛化调用与特化调用

使用说明

使用泛化调用时,建议先查看OpenAPI元数据,获取OpenAPIAPI风格、请求参数、资源路径等信息。

安装核心SDK

Terminal中执行以下命令安装核心SDK。

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

调用OpenAPI

初始化请求客户端

通过创建darabonba-openapi/v2/client对象初始化请求客户端,并通过该Client发起OpenAPI调用。在初始化客户端时,也支持使用Credentials工具,关于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表示从环境变量中获取访问密钥ID和密钥Secret
	config := &openapi.Config{
	 	AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// 设置客户端的服务接入点
	config.Endpoint = tea.String("ecs-cn-hangzhou.aliyuncs.com")
	// 初始化并返回客户端实例
	client, err := openapi.NewClient(config)
	if err != nil {
		panic(err)
	 }

	// 使用credentials默认凭证初始化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)
	// }

配置OpenAPI信息

通过openapi.Params配置OpenAPI的基本信息,比如OpenAPI的风格、API版本、请求方式等信息。

        // 配置OpenAPI的基本信息
        params := &openapi.Params{
		// 设置API的行动、版本和其他必要参数
		Action:      tea.String("DescribeRegions"), // API 名称
		Version:     tea.String("2014-05-26"), // API版本号
		Protocol:    tea.String("HTTPS"), // 请求协议:HTTPS或HTTP,建议使用HTTPS。
		Method:      tea.String("POST"), // 请求方法
		AuthType:    tea.String("AK"), // 认证类型,默认即可。当OpenAPI支持匿名请求时,您可以传入 Anonymous 发起匿名请求。
		Style:       tea.String("RPC"), // API风格:RPC或ROA。
		Pathname:    tea.String("/"), // API资源路径,RPC接口默认"/",ROA接口从OpenAPI元数据中data.path获取资源路径。
		ReqBodyType: tea.String("json"), // 请求body的类型,支持byte、json、formData。
		BodyType:    tea.String("json"), // 返回数据格式,支持json。
	}

配置请求参数

通过openapi.OpenApiRequest配置请求参数,请求参数支持通过查询参数(query)和请求体(body)传递。

请求参数传递方式

描述

query

通过查询参数传递参数。

说明

如果RPC接口的请求参数采用query传参方式,则该请求参数同样支持使用body进行传递。

body

通过请求体(body)传递参数。在使用请求体(body)传递参数时,需要根据请求体的类型设置reqBodyType的值。

        // 方式一:设置查询参数(query)
	query := map[string]interface{}{
		"InstanceChargeType": tea.String("PostPaid"),
	}
	// 创建API请求并设置参数
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(query),
	}

	// 方式二:设置请求体(body)reqBodyType的值为json格式
	// reqBody := map[string]interface{}{
	// 	"InstanceChargeType": tea.String("PostPaid"),
	// }
	// // 创建API请求并设置参数
	// request := &openapi.OpenApiRequest{
	// 	Body: util.ToJSONString(reqBody),
	// }

	// 方式三:设置请求体(body)reqBodyType的值为form-data格式
	// reqForm := map[string]interface{}{
	// 	"InstanceChargeType": tea.String("PostPaid"),
	// }
	// request := &openapi.OpenApiRequest{
	// 	// 将表单参数转为URL编码字符串
	// 	Body: openapiutil.ToForm(reqForm),
	// }

	// 方式四:设置请求体(body)reqBodyType的值为byte格式
	// bodyBytes := []byte("InstanceChargeType:PostPaid") // 示例二进制数据
	// request := &openapi.OpenApiRequest{
	// 	Body: bodyBytes,
	// }

发起请求

通过client调用call_api发起请求。

        // 设置运行时选项
	runtime := &util.RuntimeOptions{}
	// 调用API并处理返回结果
	response, err := client.CallApi(params, request, runtime)
	if err != nil {
		panic(err)
	}
	// 返回值为Map类型,可从Map中获得三类数据:body、headers、HTTP返回的状态码 statusCode。
	fmt.Println(response["body"])

代码示例

示例:调用RPC风格的API

以调用ECSDescribeRegions接口为例,展示如何使用泛化调用方式。

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() {
	// 从环境变量中获取访问密钥ID和密钥Secret
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// 设置客户端的服务接入点
	config.Endpoint = tea.String("ecs-cn-hangzhou.aliyuncs.com")
	// 初始化并返回客户端实例
	client, err := openapi.NewClient(config)
	if err != nil {
		panic(err)
	}
	params := &openapi.Params{
		// 设置API的行动、版本和其他必要参数
		Action:      tea.String("DescribeRegions"), // API名称
		Version:     tea.String("2014-05-26"), // API版本号
		Protocol:    tea.String("HTTPS"), // 请求协议:HTTPS或HTTP,建议使用HTTPS。
		Method:      tea.String("POST"), // 请求方法
		AuthType:    tea.String("AK"), // 认证类型,默认即可。当OpenAPI支持匿名请求时,您可以传入 Anonymous 发起匿名请求。
		Style:       tea.String("RPC"), // API风格:RPC、ROA
		Pathname:    tea.String("/"), // 接口 PATH,RPC接口默认"/"
		ReqBodyType: tea.String("json"), // 接口请求体内容格式。
		BodyType:    tea.String("json"), // 接口响应体内容格式。
	}

	// 设置查询参数
	query := map[string]interface{}{
		"InstanceChargeType": tea.String("PostPaid"),
	}
	// 设置运行时选项
	runtime := &util.RuntimeOptions{}
	// 创建API请求并设置参数
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(query),
	}
	// 调用API并处理返回结果
	response, err := client.CallApi(params, request, runtime)
	if err != nil {
		panic(err)
	}
	// 返回值为Map类型,可从Map中获得三类数据:body、headers、HTTP返回的状态码 statusCode。
	fmt.Println(response["body"])
}

示例:调用RESTful(ROA)风格的API

以调用容器服务查询集群列表信息为例,展示如何使用泛化调用。

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() {
	// 从环境变量中获取访问密钥ID和密钥Secret
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// Endpoint 请参考 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{
		// 接口名称
		Action: tea.String("DescribeClustersV1"),
		// 接口版本
		Version: tea.String("2015-12-15"),
		// 请求协议:HTTPS或HTTP,建议使用HTTPS。
		Protocol: tea.String("HTTPS"),
		// 接口 HTTP 方法
		Method:   tea.String("GET"),
		// 认证类型,默认即可。当OpenAPI支持匿名请求时,您可以传入 Anonymous 发起匿名请求。
		AuthType: tea.String("AK"),
		// API风格:RPC、ROA
		Style:    tea.String("ROA"),
		// API资源路径,RPC接口默认"/",ROA接口从OpenAPI元数据中data.path获取资源路径。
		Pathname: tea.String("/api/v1/clusters"),
		// 接口请求体内容格式
		ReqBodyType: tea.String("json"),
		// 接口响应体内容格式
		BodyType: tea.String("json"),
	}
	// 设置查询参数
	queries := map[string]interface{}{}
	queries["name"] = tea.String("cluster-demo")
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(queries),
	}
	// runtime options
	runtime := &util.RuntimeOptions{}
	// 返回值为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
	response, err := client.CallApi(params, request, runtime)
	if err != nil {
		panic(err)
	}
	fmt.Println(response["body"])
}