阿里雲SDK支援一種通用的方式調用OpenAPI,此方式被稱為泛化調用。本文將為您詳細介紹如何使用泛化調用訪問OpenAPI。
特點
輕量:僅需安裝阿里雲核心SDK,無需額外安裝雲產品SDK。
簡單:只需構造通用的請求參數對象,然後利用通用請求用戶端調用通用函數發起請求,調用結果也以通用格式返回。
更多介紹,請參見泛化調用與特化調用。
使用說明
使用泛化調用時,建議先查看OpenAPI中繼資料,擷取OpenAPI的API風格、請求參數、資源路徑等資訊。
安裝核心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版本、請求方式等資訊。以調用DescribeInstanceTypeFamilies介面為例:
// 配置OpenAPI的基本資料
params := &openapi.Params{
// 設定API的行動、版本和其他必要參數
Action: tea.String("DescribeInstanceTypeFamilies"), // 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或Stream傳參,如何選擇傳參方式可根據中繼資料中的介紹選擇,例如DescribeInstanceTypeFamilies的請求參數RegionId在中繼資料中資訊為{"name":"RegionId","in":"query",...}},其中"in":"query"表示RegionId通過Query傳遞。
傳參方式 | 描述 |
Query | 請求參數顯示 |
Body | 請求參數顯示 |
Stream | 在需要上傳檔案的情境,可通過Stream傳遞檔案流。 |
// 情境一:設定查詢參數(query)
query := map[string]interface{}{
"RegionId": tea.String("cn-hangzhou"),
}
// 建立API請求並設定參數
request := &openapi.OpenApiRequest{
Query: openapiutil.Query(query),
}
// 情境二:設定body參數,reqBodyType的值為json
// reqBody := map[string]interface{}{
// "param1": tea.String("value1"),
// "param2": tea.String("value2"),
// }
// // 建立API請求並設定參數
// request := &openapi.OpenApiRequest{
// Body: openapiutil.Query(reqBody),
// }
// 情境三:設定body參數,reqBodyType的值為formData
// reqForm := map[string]interface{}{
// "param1": tea.String("value1"),
// "param2": tea.String("value2"),
// }
// request := &openapi.OpenApiRequest{
// // 將表單參數轉為URL編碼字串
// Body: reqForm,
// }
// 情境四:使用Stream參數傳遞檔案流
// request := &openapi.OpenApiRequest{
// Stream: '<FILE_STREAM>', // <FILE_STREAM>需替換為實際的檔案流
// }發起請求
通過client調用CallApi發起請求。同時,在請求過程中支援設定運行時參數,例如逾時配置、代理配置等,更多資訊請查看進階配置。
// 設定運行時選項
runtime := &util.RuntimeOptions{}
// 忽略 SSL 相關報錯
// runtime.IgnoreSSL = tea.Bool(true)
// 通過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")
// 逾時參數設定,單位 ms(毫秒)
// runtime.ConnectTimeout = tea.Int(10000) // 設定連線逾時為10秒
// runtime.ReadTimeout = tea.Int(10000) // 設定讀逾時為10秒
// 調用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
以調用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() {
// 從環境變數中擷取存取金鑰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("DescribeInstanceTypeFamilies"), // 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{}{
"RegionId": tea.String("cn-hangzhou"),
}
// 設定運行時選項
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
以調用Container Service查詢叢集列表資訊為例,展示如何使用泛化調用。
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"])
}