All Products
Search
Document Center

Alibaba Cloud SDK:Integrate with Alibaba Cloud SDK V2.0 for Go

Last Updated:May 19, 2025

To facilitate API calls, we recommend that you integrate with Alibaba Cloud SDK in your project. SDKs simplify the development process, quickly integrate features, and greatly reduce the O&M cost. To integrate with Alibaba Cloud SDK, perform the following steps: install Alibaba Cloud SDK, configure an access credential, and write code for calling API operations. This topic describes how to integrate with Alibaba Cloud SDK.

Prerequisites

  • Go 1.10.x or later is installed.

1. Install the SDK for Go

  1. Log on to SDK Center and select the service whose SDK you want to use. In this example, Short Message Service (SMS) is selected.

  2. 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.image

2. Configure an access credential

To call API operations of an Alibaba Cloud service, you must configure an access credential, such as an AccessKey pair or a Security Token Service (STS) token. To prevent AccessKey pair leaks, you can record the AccessKey pair 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 used to record AccessKey pairs.

Configure environment variables in Linux and macOS

Configure environment variables by using the export command

Important

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=yourAccessKeyID
  • Configure the AccessKey secret and press Enter.

    # Replace <ACCESS_KEY_SECRET> with your AccessKey secret. 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecret
  • 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.

Configure environment variables in 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: LTAI****************

    AccessKey Secret

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

    • Variable value: yourAccessKeySecret

  • 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% and echo %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 yourAccessKeyID /M
    setx ALIBABA_CLOUD_ACCESS_KEY_SECRET yourAccessKeySecret /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% and echo %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', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::User)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [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', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::Machine)

Configure temporary environment variables. The environment variables apply only to the current session.

$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "yourAccessKeyID"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "yourAccessKeySecret"

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. Write code for calling API operations

In this example, the SendMessageToGlobe API operation of Short Message Service (SMS) is called. For more information about SendMessageToGlobe, see SendMessageToGlobe.

3.1 Initialize a request client

In the SDK, all requests to API operations are sent from a client. Before you can an API operation, you must initialize the 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.

func CreateClient () (_result *dysmsapi20180501.Client, _err error) {
  config := &openapi.Config{
    // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
    AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
    // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
    AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
  }
  config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
  _result = &dysmsapi20180501.Client{}
  _result, _err = dysmsapi20180501.NewClient(config)
  return _result, _err
}
Note

When you call the Advance operation to transfer a file stream, replace the endpoint with the region ID when you initialize the request client. The following example shows how to initialize the request client for the Facebody operation of Visual Intelligence API (VIAPI):

func CreateClient() (_result *facebody20191230.Client, _err error) {

	config := &openapi.Config{
		// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. 
		AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	config.RegionId = tea.String("cn-shanghai")
	_result, _err = facebody20191230.NewClient(config)
	return _result, _err
}

3.2 Create a request object

When you call an API operation to pass parameters, you must use the request object provided by the SDK. Name the request object of the API operation in the following format: <API operation name>Request. For example, the request object of the SendSms API operation is SendSmsRequest. For more information about the parameters, see the API reference. For more information about the parameters of the SendMessageToGlobe operation, see SendMessageToGlobe.

Note

If the API operation does not support request parameters, you do not need to create a request object. For example, the DescribeCdnSubList operation does not support request parameters.

// Create request object and set required input parameters
sendMessageToGlobeRequest := &dysmsapi20180501.SendMessageToGlobeRequest{
    // Please replace with the actual recipient number.
    To: tea.String("<YOUR_VALUE>"),
    // Please replace with the actual SMS content.
    Message: tea.String("<YOUR_VALUE>"),
  }
Note

For some API operations that require you to upload files, you can create a request object in the format of <API operation name>AdvanceRequest to pass files. The following example shows how to call the DetectBodyCount operation of Visual Intelligence API (VIAPI):

        // Replace the file path.
	filePath := `<FILE_PATH>`
	// Open the file and create a stream.
	file, err := os.Open(filePath)
	if err != nil {
		return fmt.Errorf("Failed to open the file: %v", err)
	}
	defer file.Close() // Close the file.
	// Create a request object.
	detectBodyCountAdvanceRequest := &facebody20191230.DetectBodyCountAdvanceRequest{
		ImageURLObject: file,
	}

3.3 Initiate an API request

When you use a client to call the API operation, we recommend that you name the function in the following format: <API operation name>WithOptions. This function contains two parameters: the request object and the runtime parameter. The request object is created in the preceding step. The runtime parameter is used to specify the request action, such as timeout and proxy configurations. For more information, see Advanced configuration.

Note

If the API operation does not support request parameters, you do not need to specify a request object in the request. For example, you only need to specify the runtime parameter when you call the DescribeCdnSubList operation.

 // Create runtime parameters.
 runtime := &util.RuntimeOptions{}
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    // Send a request.
    _, _err = client.SendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime)
    if _err != nil {
      return _err
    }
Note

For some API operations that require you to upload files, specify the function in the format of <API operation name>Advance. The following example shows how to call the DetectBodyCount operation of VIAPI:

// Declare the response variables.
var response *facebody20191230.DetectBodyCountResponse 
// Initiate the request.
response, _err = client.DetectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime)
fmt.Println(response)
if _err != nil {
  return _err
}

3.4 Handle exceptions

Alibaba Cloud SDK V2.0 for Go classifies exceptions into the following types:

  • error: This type of exception is caused by non-business errors. For example, an error is thrown if the verification fails because the SDK source file is modified or if the parsing fails.

  • SDKError: In most cases, this type of exception is caused by business errors.

For more information about how to handle SDK exceptions, see Exception handling.

Important

We recommend that you take proper exception handling measures, such as reporting exceptions, logging exceptions, and performing retries, to ensure the robustness and stability of your system.

Complete sample code

Sample request

package main
import (
  "encoding/json"
  "strings"
  "fmt"
  "os"
  dysmsapi20180501  "github.com/alibabacloud-go/dysmsapi-20180501/v2/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 *dysmsapi20180501.Client, _err error) {
  config := &openapi.Config{
    // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
    AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
    // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
    AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
  }
  config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
  _result = &dysmsapi20180501.Client{}
  _result, _err = dysmsapi20180501.NewClient(config)
  return _result, _err
}

func _main (args []*string) (_err error) {
  client, _err := CreateClient()
  if _err != nil {
    return _err
  }

  // Create request object and set required input parameters
sendMessageToGlobeRequest := &dysmsapi20180501.SendMessageToGlobeRequest{
    // Please replace with the actual recipient number.
    To: tea.String("<YOUR_VALUE>"),
    // Please replace with the actual SMS content.
    Message: tea.String("<YOUR_VALUE>"),
  }
  runtime := &util.RuntimeOptions{}
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    // Copy the code to run, please print the return value of the API by yourself.
    _, _err = client.SendMessageToGlobeWithOptions(sendMessageToGlobeRequest, 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())
    }
    // Only a printing example. Please be careful about exception handling and do not ignore exceptions directly in engineering projects.
    // print error message
    fmt.Println(tea.StringValue(error.Message))
    // Please click on the link below for diagnosis.
    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)
  }
}

Sample request that requires file upload through the Advance operation

package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	facebody20191230 "github.com/alibabacloud-go/facebody-20191230/v5/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

func CreateClient() (_result *facebody20191230.Client, _err error) {

	config := &openapi.Config{
		// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. 
		AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	config.RegionId = tea.String("cn-shanghai")
	_result, _err = facebody20191230.NewClient(config)
	return _result, _err
}

func _main() (_err error) {
	client, _err := CreateClient()
	if _err != nil {
		return _err
	}

	// Replace the file path.
	filePath := `<FILE_PATH>`
	// Open the file and create a stream.
	file, err := os.Open(filePath)
	if err != nil {
		return fmt.Errorf("Failed to open the file: %v", err)
	}
	defer file.Close() // Close the file.
	// Create a request object.
	detectBodyCountAdvanceRequest := &facebody20191230.DetectBodyCountAdvanceRequest{
		ImageURLObject: file,
	}
	runtime := &util.RuntimeOptions{}
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		var response *facebody20191230.DetectBodyCountResponse // Declare the response variables.
		// Initiate the request.
		response, _err = client.DetectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime)
		fmt.Println(response)
		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. 
		// Return error messages.
		fmt.Println(tea.StringValue(error.Message))
		//The URL that is used for troubleshooting.
		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()
	if err != nil {
		panic(err)
	}
}

FAQ

  1. How do I handle the "You are not authorized to perform this operation" error thrown by an API operation?

    Possible causes and solutions

    Possible causes: The AccessKey pair of the Resource Access Management (RAM) user does not have the permissions to call the API operation.

    Solutions: Grant the required permissions to the RAM user. For more information, see Grant permissions to a RAM user.

    For example, if the "You are not authorized to perform this operation" error is thrown by the SendMessageToGlobe API operation, create the following custom policy to grant the required permissions to the RAM user:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendMessageToGlobe",
          "Resource": "*"
        }
      ]
    }
  2. How do I handle the "SDKError: Message: Post "https://ecs-cn-XX.aliyuncs.com": dial tcp: lookup ecs-cn-XX.aliyuncs.com: no such host" error thrown by an API operation?

    Possible causes and solutions

    Possible causes: The API operation does not support the endpoint that you specify when you initialize the request client.

    Solutions: Specify a supported endpoint and try again. For more information, see Configure an endpoint.

  3. How do I handle the "SDKError: StatusCode: 404 Code: InvalidAccessKeyId.NotFound Message: code: 404, Specified access key is not found" error thrown by an API operation?

    Possible causes and solutions

    Possible causes: The AccessKey pair is not correctly passed to the request.

    Solutions: Make sure that the AccessKey pair is correctly passed when you initialize the request client. The XXX value of os.Getenv("XXX") is obtained form the environment variable.

For more information about how to handle SDK exceptions, see FAQ.