Integrate the SDK

更新时间:
复制 MD 格式

Integrate the Alibaba Cloud SDK into your Go project to call OpenAPI operations. The process covers three steps: import the SDK, set access credentials, and call the API.

Prerequisites

  • Go 1.10 or later.

Import the SDK

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

  2. On the Installation page, for SDK Generation, select V2.0, and for All Languages, select Go. Then, on the Quick Start tab, you can find the SDK installation method for Short Message Service (SMS).image

Set access credentials

Alibaba Cloud OpenAPI calls require access credentials such as an AccessKey or a Security Token Service (STS) token. Store credentials in environment variables to prevent leaks. Security best practices are covered in Securely use access credentials. The following example uses ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET:

Configure on Linux and macOS

Configure environment variables 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

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.

Using 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.

Use the SDK

The following example calls the SendSms API of Short Message Service (SMS). SendSms API reference: SendSms .

1. Initialize the request client

All V2.0 SDK OpenAPI calls go through a request client. This example initializes the client with an AccessKey. Other initialization methods are described in Manage access credentials.

Important
  • The client instance is thread-safe. You do not need a separate instance per thread.

  • Avoid creating client objects repeatedly — this wastes resources and degrades performance. Use the singleton pattern to ensure one client per credential-and-endpoint pair throughout the application lifecycle.

import (
  "os"

  openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
  "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.
    AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
    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
}

2. Create a Request struct instance

Pass API parameters through the SDK's `Request` struct, named <OpenAPI name>Request (for example, `SendSmsRequest` for the `SendSms` API). Parameter details: SendSms .

Note

APIs without request parameters (such as DescribeCdnSubList) do not require a request object.

// Create a request and set its parameters.
sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
  // The code of the SMS template.
  TemplateCode: tea.String("<YOUR_VALUE>"),
  // The value of the variables in the SMS template. Example: {"code":"1234"}
  TemplateParam: tea.String("<YOUR_VALUE>"),
  // The mobile phone numbers of the recipients.
  PhoneNumbers: tea.String("<YOUR_VALUE>"),
  // The SMS signature.
  SignName: tea.String("<YOUR_VALUE>"),
}

3. Send the request

Call an OpenAPI using the <APIName>WithOptions function, which takes a pointer to the API Request struct and a pointer to the runtime options struct. Runtime options control timeouts, proxies, and other request behaviors. Advanced configurations.

Note

For APIs without request parameters (such as DescribeCdnSubList), pass only the runtime options.

// Add util "github.com/alibabacloud-go/tea-utils/v2/service" to your imports.

func _main() (_result *dysmsapi20170525.SendSmsResponse, _err error) {
  client, _err := CreateClient()
  if _err != nil {
    return nil, _err
  }
  // Create an instance of the SendSmsRequest struct.
  sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
    // Replace this with your SMS template code.
    TemplateCode: tea.String("<YOUR_VALUE>"),
    // Replace this with the actual values for the variables in your SMS template. Example: {"code":"1234"}
    TemplateParam: tea.String("<YOUR_VALUE>"),
    // Replace this with the recipient's mobile phone number.
    PhoneNumbers: tea.String("<YOUR_VALUE>"),
    // Replace this with your SMS signature.
    SignName: tea.String("<YOUR_VALUE>"),
  }
  // Create an instance of the RuntimeOptions struct.
  runtime := &util.RuntimeOptions{}
  response, _err := client.SendSmsWithOptions(sendSmsRequest, runtime)
  if _err != nil {
    return nil, _err
  }
  return response, nil
}

4. Handle exceptions

The V2.0 Go SDK categorizes 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.

Detailed exception handling guidance is in Handle exceptions.

Important

Always handle exceptions by propagating, logging, or recovering from them to ensure system stability.

Click to view the complete code example

SendSms API Call Examples

package main

import (
  "fmt"
  "os"

  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. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your runtime environment.
    AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
    // Required. Ensure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your 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
}

func _main() (_result *dysmsapi20170525.SendSmsResponse, _err error) {
  client, _err := CreateClient()
  if _err != nil {
    return nil, _err
  }
  // Create a request object and set the input parameters.
  sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
    // The code of your SMS template.
    TemplateCode: tea.String("<YOUR_VALUE>"),
    // The actual values of the variables in your SMS template. Example: {\"code\":\"1234\"}
    TemplateParam: tea.String("<YOUR_VALUE>"),
    // The recipient's mobile phone number.
    PhoneNumbers: tea.String("<YOUR_VALUE>"),
    // Your SMS signature.
    SignName: tea.String("<YOUR_VALUE>"),
  }
  runtime := &util.RuntimeOptions{}
  response, _err := client.SendSmsWithOptions(sendSmsRequest, runtime)
  if _err != nil {
    return nil, _err
  }
  return response, nil
}

func main() {
  response, err := _main()
  if err != nil {
    panic(err)
  }
  // Print the response.
  fmt.Println(response.String())
}

Special scenario: Configure the Advance API for file uploads

Some cloud products (such as Image Search and Visual Intelligence API) require the Advance API for local file uploads. This API accepts a file stream, temporarily stores the file in Alibaba Cloud OSS (default region: cn-shanghai), and processes it. This example uses the DetectBodyCount API from the Visual Intelligence API.

Note

Temporary files stored in Alibaba Cloud OSS are deleted periodically.

  1. 1. Initialize the request client

    Set both RegionId and Endpoint. RegionId specifies the OSS region for temporary file storage. Omitting RegionId may cause timeouts if the product and OSS are 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 instance of the AdvanceRequest struct

    Use the AdvanceRequest struct (named <APIName>AdvanceRequest) to pass the file stream. The file stream parameter has type io.Reader.

    // 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 a request

    Call <APIName>Advance with 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.

    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. Manage RAM user permissions.

    For example, if this error occurs when calling the SendSms API, create a custom policy and grant it to the RAM user:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendSms",
          "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.

    Cause and solution

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

    Solution: Modify the Endpoint and retry. Configure endpoints.

  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.

    Cause and solution

    Cause: The AccessKey was not passed correctly.

    Solution: Verify that the AccessKey is passed correctly during client initialization. os.Getenv("XXX") retrieves the value of XXX from environment variables.

Other common SDK errors and solutions: FAQ.