All Products
Search
Document Center

Alibaba Cloud SDK:Integrate the SDK

Last Updated:Sep 21, 2026

When you call OpenAPI operations, we recommend that you integrate the SDK into your project. Using the SDK simplifies development, enables fast feature integration, and reduces maintenance costs. Integrating the Alibaba Cloud SDK involves three steps: import the Alibaba Cloud SDK, set access credentials, and use the SDK. This topic describes the SDK integration process in detail.

Prerequisites

  • Go 1.10.x or later

Import the SDK

  1. Log on to the SDK Center and select the product whose API you want to call, such as Short Message Service (SMS).

  2. On the Installation page, and for All Languages, select Go. On the Quick Start tab, you can get the SDK installation method for Short Message Service (SMS).

    Command to install the SDK core library: go get github.com/alibabacloud-go/darabonba-openapi/v2/client. Command to install the Short Message Service (SMS) SDK: go get github.com/alibabacloud-go/dysmsapi-20170525/v4. Release and source code repository: https://github.com/alibabacloud-go/dysmsapi-20170525/.

Set access credentials

Calling Alibaba Cloud OpenAPI usually requires setting access credentials. Common credential types are AccessKey (AK) and Security Token Service token (STS token). To prevent credential leaks, a common solution is to store them in environment variables. For more security solutions, see Securely use access credentials. This topic uses the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as an example. Configure them as follows.

Configure on Linux and macOS

Set an Alibaba Cloud AccessKey in environment variables on Linux and macOS

This section uses the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as examples. You can replace the variable names as needed, for example, OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.

Configure environment variables by using the export command:

Important

A temporary environment variable set using the export command is valid only for the current session. The variable is cleared when the session ends. For long-term retention (LTR), add the export command to the startup configuration file of your operating system.

  • Configure the AccessKey ID and press Enter.

    # Replace yourAccessKeyID with your AccessKey ID.
    export ALIBABA_CLOUD_ACCESS_KEY_ID=yourAccessKeyID
  • Configure the AccessKey secret and press Enter.

    # Replace yourAccessKeySecret with your AccessKey secret.
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecret
  • Verify the configuration.

    Run the echo $ALIBABA_CLOUD_ACCESS_KEY_ID command. If the command returns the correct AccessKey ID, the configuration is successful.

Configure on Windows

Set an Alibaba Cloud AccessKey in environment variables on Windows

This section uses the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as examples. You can replace the variable names as needed, for example, OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.

Use the graphical user interface (GUI)

  • Procedure

    The following steps describe how to set environment variables using the GUI in Windows 10.

    On your desktop, right-click This PC and choose Properties > Advanced system settings > Environment Variables > New under System variables or User variables. Then, complete the configuration.

    Variable

    Example value

    AccessKey ID

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

    • Variable value: yourAccessKeyID

    AccessKey secret

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

    • Variable value: yourAccessKeySecret

  • Test the configuration

    Click Start (or use the Win+R keyboard shortcut), click Run, enter `cmd`, and then click OK (or press Enter) to open the command prompt. Run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the commands return the correct AccessKey, the configuration is successful.

Use the command prompt (CMD)

  • Procedure

    Open the command prompt as an administrator and run the following commands to add new environment variables to the system.

    setx ALIBABA_CLOUD_ACCESS_KEY_ID yourAccessKeyID /M
    setx ALIBABA_CLOUD_ACCESS_KEY_SECRET yourAccessKeySecret /M

    The /M parameter indicates a system environment variable. You can omit this parameter when you set a user environment variable.

  • Test the configuration

    Click Start (or use the Win+R keyboard shortcut), click Run, enter `cmd`, and then click OK (or press Enter) to open the command prompt. Run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the commands return the correct AccessKey, the configuration is successful.

Use Windows PowerShell

In PowerShell, you can set new environment variables that are valid for 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)

To set environment variables for all users, you must have administrative permissions:

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::Machine)

You can set temporary environment variables that are valid only for 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 commands return the correct AccessKey, the configuration is successful.

Important

After you configure the environment variables, you may need to restart your development tools, such as integrated development environments (IDEs), or services for the new settings to take effect.

Use the SDK

This topic uses the SendMessageToGlobe API of Short Message Service (SMS) as an example. For the API reference of the SendMessageToGlobe API, see SendMessageToGlobe.

1. Initialize the request client

In the V2.0 SDK, all OpenAPI calls are initiated through a request client (Client) provided by the SDK. Therefore, you must initialize the request client before you call an OpenAPI operation. The request client supports multiple initialization methods. This example uses an AccessKey for initialization. For more initialization methods, see Manage access credentials.

Important
  • Thread safety: The client instance is thread-safe and can be used safely in a multi-threaded environment. You do not need to create a separate instance for each thread.

  • In actual development, we do not recommend creating client objects frequently. This wastes resources and degrades performance. We recommend that you use the singleton pattern to wrap the client so that only one client object is initialized for the same access credentials and Endpoint throughout the application lifecycle.

import (
  "os"

  openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  dysmsapi20180501 "github.com/alibabacloud-go/dysmsapi-20180501/v2/client"
  "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
}

2. Create a request struct instance

When you call an OpenAPI operation to pass parameters, use the Request struct provided by the SDK. The naming format of the OpenAPI Request struct is <OpenAPI name>Request. For example, the request object of the SendSms API is SendSmsRequest. For more information about the request parameters, see the corresponding API reference. For the API reference used in this example, see SendMessageToGlobe.

Note

If the OpenAPI operation does not support request parameters, you do not need to create a request object. For example, when you call DescribeCdnSubList, this API 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>"),
}

3. Send the request

When you call an OpenAPI operation through the request client, (Recommended) use the <API name>WithOptions function. This function takes two parameters: the first parameter is a pointer to the API Request struct, and the second parameter is a pointer to the runtime options struct. Runtime options configure request behaviors, such as timeout settings and proxy configurations. For more information, see Advanced configurations.

Note

If the OpenAPI operation does not support request parameters, you do not need to pass a request object when you send the request. For example, when you call DescribeCdnSubList, this API only requires the runtime options.

// You need to add util "github.com/alibabacloud-go/tea-utils/v2/service" to the import.

func _main() (_result *dysmsapi20180501.SendMessageToGlobeResponse, _err error) {
  client, _err := CreateClient()
  if _err != nil {
    return nil, _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{}
  // To run the code, copy it and print the API return value.
  response, _err := client.SendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime)
  if _err != nil {
    return nil, _err
  }
  return response, _err
}

4. Handle exceptions

The V2.0 Go SDK classifies exceptions into two main types: error and SDKError.

  • error: Non-business errors, such as validation errors caused by modified SDK source files or parsing errors.

  • SDKError: Business-related errors.

For more information about exception handling, see Handle exceptions.

Important

We recommend that you take reasonable measures to handle exceptions, such as properly propagating exceptions, logging, and attempting recovery, to ensure the robustness and stability of your system.

Click to view the complete code example

SendMessageToGlobe API call example

package main

import (
  "fmt"
  openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  dysmsapi20180501 "github.com/alibabacloud-go/dysmsapi-20180501/v2/client"
  util "github.com/alibabacloud-go/tea-utils/v2/service"
  "github.com/alibabacloud-go/tea/tea"
  "os"
)

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() (_result *dysmsapi20180501.SendMessageToGlobeResponse, _err error) {
  client, _err := CreateClient()
  if _err != nil {
    return nil, _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{}
  // To run the code, copy it and print the API return value.
  response, _err := client.SendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime)
  if _err != nil {
    return nil, _err
  }
  return response, _err
}

func main() {
  response, err := _main()
  if err != nil {
    panic(err)
  }
  fmt.Println(response.Body)
}

Special scenario: Configure the Advance API for file uploads

When you use cloud products such as Image Search and Visual Intelligence API to process local images or upload images, the OpenAPI operations provided in the official documentation do not support uploading files directly. To upload a file, you can use the Advance API provided by the cloud product, which supports passing a file stream object. The underlying mechanism is: the cloud product temporarily stores the uploaded file in Alibaba Cloud OSS, with the default storage region being cn-shanghai, and implements the related feature by reading the temporary file from that OSS. This example uses the DetectBodyCount API of Visual Intelligence API, and the procedure is as follows.

Note

Temporary files stored in Alibaba Cloud OSS are deleted periodically.

  1. Initialize the request client

    Note that you need to set both RegionId and the Endpoint of the cloud product. RegionId specifies the region where the temporary file is stored in OSS. If RegionId is not set, timeouts may occur when you call the OpenAPI operation, because the cloud product and OSS may be in different regions.

    import (
      "os"
    
      openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      facebody20191230 "github.com/alibabacloud-go/facebody-20191230/v5/client"
      "github.com/alibabacloud-go/tea/tea"
    )
    
    func CreateClient() (_result *facebody20191230.Client, _err error) {
      config := &openapi.Config{
        // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
        AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
        // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
        AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
      }
      // The endpoint and regionId must be set to the same region.
      config.RegionId = tea.String("cn-shanghai")
      config.Endpoint = tea.String("facebody.cn-shanghai.aliyuncs.com")
      _result, _err = facebody20191230.NewClient(config)
      return _result, _err
    }
  2. Create an AdvanceRequest struct instance

    When you upload a local file, you need to use the AdvanceRequest struct provided by the SDK to pass the file stream. The naming format of the AdvanceRequest struct is <OpenAPI name>AdvanceRequest. For the name of the parameter that passes the file stream, find the parameter whose type is io.Reader in the corresponding AdvanceRequest struct.

    // Replace with 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 file: %v", err)
    }
    defer file.Close() // Close the file.
    // Create an AdvanceRequest struct instance.
    detectBodyCountAdvanceRequest := &facebody20191230.DetectBodyCountAdvanceRequest{
      ImageURLObject: file,
    }
  3. Send the request

    Call the <API name>Advance function to send the request. The input parameter is a pointer to the AdvanceRequest struct.

    // You need to add util "github.com/alibabacloud-go/tea-utils/v2/service" to the import.
    
    func _main() (response *facebody20191230.DetectBodyCountResponse, _err error) {
      client, _err := CreateClient()
      if _err != nil {
        return nil, _err
      }
    
      // Replace with the file path.
      filePath := `<FILE_PATH>`
      // Open the file and create a stream.
      file, err := os.Open(filePath)
      if err != nil {
        return nil, fmt.Errorf("Failed to open file: %v", err)
      }
      defer file.Close() // Close the file.
      // Create a request object.
      detectBodyCountAdvanceRequest := &facebody20191230.DetectBodyCountAdvanceRequest{
        ImageURLObject: file,
      }
      runtime := &util.RuntimeOptions{}
      // Send the request.
      response, _err = client.DetectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime)
    
      if _err != nil {
        return nil, _err
      }
      return response, nil
    }

Click to view the complete code example

package main

import (
  "fmt"
  "os"

  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 ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
    AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
    AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
  }
  config.RegionId = tea.String("cn-shanghai")
  config.Endpoint = tea.String("facebody.cn-shanghai.aliyuncs.com")
  _result, _err = facebody20191230.NewClient(config)
  return _result, _err
}

func _main() (response *facebody20191230.DetectBodyCountResponse, _err error) {
  client, _err := CreateClient()
  if _err != nil {
    return nil, _err
  }

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

  if _err != nil {
    return nil, _err
  }
  return response, nil
}
func main() {
  response, err := _main()
  if err != nil {
    panic(err)
  }
  fmt.Println(response)
}

FAQ

  1. The error message "You are not authorized to perform this operation" is returned when I call an OpenAPI operation.

    Cause and solution

    Cause: The Resource Access Management (RAM) user that corresponds to your AccessKey does not have the required permissions to call the API.

    Solution: Grant the required OpenAPI permissions to the RAM user. For information about how to grant permissions to a RAM user, see Manage RAM user permissions.

    For example, if the error "You are not authorized to perform this operation" occurs when you call the SendMessageToGlobe API, you can create a custom access policy and grant it to the RAM user.

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendMessageToGlobe",
          "Resource": "*"
        }
      ]
    }
  2. The error message "SDKError: Message: Post "https://ecs-cn-XX.aliyuncs.com": dial tcp: lookup ecs-cn-XX.aliyuncs.com: no such host" is returned when I call an OpenAPI operation.

    Cause and solution

    Cause: The Endpoint that you specified during client initialization is not supported by the OpenAPI operation that you are calling.

    Solution: See Configure endpoints. Modify the Endpoint and call the OpenAPI operation again.

  3. The error message "SDKError: StatusCode: 404 Code: InvalidAccessKeyId.NotFound Message: code: 404, Specified access key is not found." is returned when I call an OpenAPI operation.

    Cause and solution

    Cause: Your AccessKey was not passed correctly.

    Solution: Check whether the AccessKey is passed correctly when you initialize the request client. Note that os.Getenv("XXX") retrieves the value of XXX from environment variables.

For solutions to more errors that occur when you use the SDK, see FAQ.