To integrate Alibaba Cloud SDK V2.0, you must perform the following steps: configure an access credential, import the SDK to your project, and write code for calling API operations. This topic describes how to integrate Alibaba Cloud SDK V2.0. In this example, Alibaba Cloud SDK V2.0 for Go
is used to call the SendSms operation of Short Message Service (SMS) to send a text message.
Prerequisites
Go 1.10.x or later is installed.
1. Install the SDK for Go
Install the SDK for specialized calls
Alibaba Cloud SDK V2.0 incorporates the main API logic, such as parameter processing, request assembly, and response processing. You can make API requests by installing the SDK of an Alibaba Cloud service as a dependency.
Log on to SDK Center and select the service whose SDK you want to use. In this example, Short Message Service (SMS) is selected.
On the Short Message Service page, select Go in the All languages section. On the Quick Start tab, obtain the installation method of Short Message Service (SMS) SDK.
Install the SDK for generic calls
You do not need to install the SDK of a service to make generic calls. You need to only import the github.com/alibabacloud-go/darabonba-openapi/v2/client
core package. For information about the latest version of the core package, see darabonba-openapi. Run the following command to install the core package:
go get github.com/alibabacloud-go/darabonba-openapi/v2/client
2. Configure an access credential
You must configure an access credential before you use Alibaba Cloud SDK V2.0 to call API operations. The following types of credentials are commonly used on Alibaba Cloud: AccessKey pairs
and Security Token Service (STS) tokens
. For more information, see Credential. To prevent leaks of credentials, you can configure the information about credentials in environment variables. For more information about other security solutions, see Credential security solutions. In this example, the ALIBABA_CLOUD_ACCESS_KEY_ID
and ALIBABA_CLOUD_ACCESS_KEY_SECRET
environment variables are configured.
Linux and macOS
Configure environment variables by using the export command
The temporary environment variables configured by using the export command are valid only for the current session. After you exit the session, the configured environment variables become invalid. To configure permanent environment variables, you can add the export command to the startup configuration file of the corresponding operating system.
Configure the AccessKey ID and press Enter.
# Replace <ACCESS_KEY_ID> with your AccessKey ID. export ALIBABA_CLOUD_ACCESS_KEY_ID=<ACCESS_KEY_ID>
Configure the AccessKey secret and press Enter.
# Replace <ACCESS_KEY_SECRET> with your AccessKey secret. export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET>
Check whether the configuration is successful.
Run the
echo $ALIBABA_CLOUD_ACCESS_KEY_ID
command. If the valid AccessKey ID is returned, the environment variables are configured.
Windows
Use GUI
Procedure
If you want to use GUI to configure environment variables in Windows 10, perform the following steps:
On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section. Then, configure the variables described in the following table.
Variable
Example
AccessKey ID
Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID
Variable value: LTAI4GDty8ab9W4Y1D****
AccessKey Secret
Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET
Variable value: IrVTNZNy5yQelTETg0cZML3TQn****
Check whether the configuration is successful.
On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the
echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
andecho %ALIBABA_CLOUD_ACCESS_KEY_SECRET%
commands. If the valid AccessKey pair is returned, the configuration is successful.
Use CMD
Procedure
Open a Command Prompt window as an administrator and run the following commands to add environment variables in the operating system:
setx ALIBABA_CLOUD_ACCESS_KEY_ID LTAI4GDty8ab9W4Y1D**** /M setx ALIBABA_CLOUD_ACCESS_KEY_SECRET IrVTNZNy5yQelTETg0cZML3TQn**** /M
/M
indicates that the environment variable is of system level. You can choose not to use this parameter when you configure a user-level environment variable.Check whether the configuration is successful.
On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the
echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
andecho %ALIBABA_CLOUD_ACCESS_KEY_SECRET%
commands. If the valid AccessKey pair is returned, the configuration is successful.
Use Windows PowerShell
In PowerShell, configure new environment variables. The environment variables apply to all new sessions.
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::User)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::User)
Configure environment variables for all users. You must run the following commands as an administrator.
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::Machine)
Configure temporary environment variables. The environment variables apply only to the current session.
$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "LTAI4GDty8ab9W4Y1D****"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "IrVTNZNy5yQelTETg0cZML3TQn****"
In PowerShell, run the Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_ID
and Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_SECRET
commands. If the valid AccessKey pair is returned, the configuration is successful.
3. Call an API operation
In this example, the sample code of a specialized call is used. For more information about how to make a generic call, see Generic calls.
3.1 Initialize a request client
You can use multiple methods to initialize a request client. In this example, an AccessKey pair is used to initialize a request client. For more information, see Manage access credentials.
package main
import (
dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
)
func CreateClient () (_result *dysmsapi20170525.Client, _err error) {
// If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your Alibaba Cloud account may be compromised. The following lines are provided for reference only.
config := &openapi.Config{
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
_result = &dysmsapi20170525.Client{}
_result, _err = dysmsapi20170525.NewClient(config)
return _result, _err
}
3.2 Create a request object and configure runtime configurations
In most cases, you can create a request object and specify the parameters based on your business requirements. You can also customize runtime configurations.
// Create a request object and specify the parameters.
sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
// The code of the SMS template.
TemplateCode: tea.String("<YOUR_VALUE>"),
// The variables of the SMS template. Example: {\"code\":\"1234\"}.
TemplateParam: tea.String("{\"code\":\"1234\"}"),
// The mobile numbers to which you want to send a text message.
PhoneNumbers: tea.String("<YOUR_VALUE>"),
// The name of the SMS signature.
SignName: tea.String("<YOUR_VALUE>"),
}
// Create a runtime configuration object.
runtime := &util.RuntimeOptions{}
3.3 Initiate an API request
In Alibaba Cloud SDK V2.0, the client of each Alibaba Cloud service contains all the API operations provided by the service. In addition, Alibaba Cloud SDK V2.0 provides three methods to define each API operation. This design aims to improve the flexibility and efficiency of development, and ensure that you can call API operations in an optimal way based on your project requirements.
The name of the API operation is in lowercase letters.
<API operation name>
: uses the default runtime configurations to initiate a request. You do not need to specify runtime parameters.package main import ( "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" ) func CreateClient() (_result *dysmsapi20170525.Client, _err error) { config := &openapi.Config{ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")), // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")), } // The endpoint. For more information, visit https://api.aliyun.com/product/Dysmsapi. config.Endpoint = tea.String("dysmsapi.aliyuncs.com") _result = &dysmsapi20170525.Client{} _result, _err = dysmsapi20170525.NewClient(config) return _result, _err } func main() { client, _err := CreateClient() if _err != nil { panic(_err) } sendSmsRequest := &dysmsapi20170525.SendSmsRequest{ // The code of the SMS template. TemplateCode: tea.String("<YOUR_VALUE>"), // The variables of the SMS template. Example: {\"code\":\"1234\"}. TemplateParam: tea.String("{\"code\":\"1234\"}"), // The mobile numbers to which you want to send a text message. PhoneNumbers: tea.String("<YOUR_VALUE>"), // The name of the SMS signature. SignName: tea.String("<YOUR_VALUE>"), } resp, tryErr := func() (response *dysmsapi20170525.SendSmsResponse, _e error) { defer func() { if r := tea.Recover(recover()); r != nil { _e = r } }() // If you copy and run the sample code, write your own code to display the response of the API operation. response, _err = client.SendSms(sendSmsRequest) if _err != nil { return response, _err } return response, nil }() if tryErr != nil { if sdkError, ok := tryErr.(*tea.SDKError); ok { // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error message displayed in this example is for reference only. fmt.Println(tea.StringValue(sdkError.Message)) fmt.Println(tea.StringValue(sdkError.Code)) fmt.Println(tea.StringValue(sdkError.Data)) } else { // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error message displayed in this example is for reference only. fmt.Println(tea.String(tryErr.Error())) } } else { fmt.Println("Response:", resp) // The response. } }
<API operation name>WithOptions
: uses the custom runtime configurations to initiate a request. For more information, see Advanced configuration.package main import ( "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" ) func CreateClient() (_result *dysmsapi20170525.Client, _err error) { config := &openapi.Config{ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")), // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")), } // The endpoint. For more information, visit https://api.aliyun.com/product/Dysmsapi. config.Endpoint = tea.String("dysmsapi.aliyuncs.com") _result = &dysmsapi20170525.Client{} _result, _err = dysmsapi20170525.NewClient(config) return _result, _err } func main() { client, _err := CreateClient() if _err != nil { panic(_err) } sendSmsRequest := &dysmsapi20170525.SendSmsRequest{ // The code of the SMS template. TemplateCode: tea.String("<YOUR_VALUE>"), // The variables of the SMS template. Example: {\"code\":\"1234\"}. TemplateParam: tea.String("{\"code\":\"1234\"}"), // The mobile numbers to which you want to send a text message. PhoneNumbers: tea.String("<YOUR_VALUE>"), // The name of the SMS signature. SignName: tea.String("<YOUR_VALUE>"), } runtime := &util.RuntimeOptions{} resp, tryErr := func() (response *dysmsapi20170525.SendSmsResponse, _e error) { defer func() { if r := tea.Recover(recover()); r != nil { _e = r } }() // If you copy and run the sample code, write your own code to display the response of the API operation. response, _err = client.SendSmsWithOptions(sendSmsRequest, runtime) if _err != nil { return response, _err } return response, nil }() if tryErr != nil { if sdkError, ok := tryErr.(*tea.SDKError); ok { // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error message displayed in this example is for reference only. fmt.Println(tea.StringValue(sdkError.Message)) fmt.Println(tea.StringValue(sdkError.Code)) fmt.Println(tea.StringValue(sdkError.Data)) } else { // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error message displayed in this example is for reference only. fmt.Println(tea.String(tryErr.Error())) } } else { fmt.Println("Response:", resp) // The response. } }
<API operation name>Advance
: used for API operations that require file uploading. By default, you must specify runtime parameters. The following sample code provides an example on how to initiate a request to upload a file and call an API operation to usethe human face and body recognition feature of Visual Intelligence API (VIAPI)
.go get github.com/alibabacloud-go/facebody-20191230/v5
package main import ( "encoding/json" "strings" "fmt" "os" facebody20191230 "github.com/alibabacloud-go/facebody-20191230/v5/client" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" ) func CreateClient () (_result *facebody20191230.Client, _err error) { // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your Alibaba Cloud account may be compromised. The following lines are provided for reference only. config := &openapi.Config{ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")), // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")), } config.Endpoint = tea.String("facebody.cn-shanghai.aliyuncs.com") _result = &facebody20191230.Client{} _result, _err = facebody20191230.NewClient(config) return _result, _err } func _main (args []*string) (_err error) { client, _err := CreateClient() if _err != nil { return _err } // The file path. file, _err := os.Open("<filepath>") if _err != nil { panic(_err) } // Initialize a request to call the DescribeRegions operation. detectBodyCountAdvanceRequest := &facebody20191230.DetectBodyCountAdvanceRequest{ ImageURLObject: file, } // Configure the runtime object. runtime := &util.RuntimeOptions{} tryErr := func()(_e error) { defer func() { if r := tea.Recover(recover()); r != nil { _e = r } }() // If you copy and run the sample code, write your own code to display the response of the API operation. _, _err = client.DetectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime) if _err != nil { return _err } return nil }() if tryErr != nil { var error = &tea.SDKError{} if _t, ok := tryErr.(*tea.SDKError); ok { error = _t } else { error.Message = tea.String(tryErr.Error()) } // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error message displayed in this example is for reference only. // The error message. fmt.Println(tea.StringValue(error.Message)) // The URL of the corresponding error diagnostics. var data interface{} d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data))) d.Decode(&data) if m, ok := data.(map[string]interface{}); ok { recommend, _ := m["Recommend"] fmt.Println(recommend) } _, _err = util.AssertAsString(error.Message) if _err != nil { return _err } } return _err } func main() { err := _main(tea.StringSlice(os.Args[1:])) if err != nil { panic(err) } }