All Products
Search
Document Center

Alibaba Cloud SDK:Integrate the SDK

Last Updated:Jun 02, 2026

Integrate the Alibaba Cloud SDK into your project to simplify OpenAPI calls and reduce maintenance costs. SDK integration involves three steps: import the SDK, set access credentials, and call the API.

Environment requirements

Python 3.7 or later.

Import the SDK

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

  2. On the Installation page, and for All Languages, select Python. 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, typically an AccessKey (AK) or Security Token Service (STS) token. Store credentials in environment variables to prevent leakage. Secure use of access credentials. The following example uses the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables:

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 and SendMessageToGlobe API of Short Message Service (SMS). API reference: SendMessageToGlobe — , SendMessageToGlobe.

1. Initialize the request client

All API requests are sent through a client. Initialize the client before calling any API. This example uses an AccessKey. Other initialization methods are described in Manage access credentials.

Important
  • Client objects such as or Dysmsapi20180501Client instances are thread-safe and can be shared across threads.

  • Avoid creating client objects repeatedly. Use the singleton pattern to maintain one client instance per set of credentials and endpoint throughout the application lifecycle.

@staticmethod
def create_client() -> Dysmsapi20180501Client:
    config = open_api_models.Config(
           # Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.,
           access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
           # Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.,
           access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
      # See https://api.alibabacloud.com/product/Dysmsapi.
      config.endpoint = f'dysmsapi.aliyuncs.com'
      return Dysmsapi20180501Client(config)

2. Create a request object

Pass parameters through the SDK request object, named <API operation name>Request (for example, SendSmsRequest). Parameter details: , SendMessageToGlobe.

Note

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

# Create request object and set required input parameters
send_message_to_globe_request = dysmsapi_20180501_models.SendMessageToGlobeRequest(
           # Please replace with the actual recipient number.
           to='<YOUR_NUMBER>',
           # Please replace with the actual SMS content.
           message='<YOUR_MESSAGE>'
)

3. Send the request

Call the API using <api_name>_with_options, where <api_name> is the OpenAPI name in snake_case. This function takes the request object and a runtime options object for timeout and proxy settings. Advanced Configurations.

Note

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

# Create runtime parameters.
runtime = util_models.RuntimeOptions()
client = create_client()
# Send a request.
client.send_message_to_globe_with_options(send_message_to_globe_request, runtime)

4. Handle exceptions

The V2.0 Python SDK classifies exceptions into two main types: TeaUnretryableException and TeaException.

  • TeaUnretryableException: Thrown after all retries for a network issue are exhausted.

  • TeaException: Thrown for service-side errors.

Exception handling.

Important

Always handle exceptions properly — propagate, log, or recover — to ensure system stability.

Click to view the complete code example

SendMessageToGlobe API call examples

import os
import sys
from typing import List
from alibabacloud_dysmsapi20180501.client import Client as Dysmsapi20180501Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20180501 import models as dysmsapi_20180501_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Dysmsapi20180501Client:
            config = open_api_models.Config(
            # Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.,
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.,
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        # See https://api.alibabacloud.com/product/Dysmsapi.
        config.endpoint = f'dysmsapi.aliyuncs.com'
        return Dysmsapi20180501Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        # Create request object and set required input parameters
        send_message_to_globe_request = dysmsapi_20180501_models.SendMessageToGlobeRequest(
           # Please replace with the actual recipient number.
           to='<YOUR_NUMBER>',
           # Please replace with the actual SMS content.
           message='<YOUR_MESSAGE>'
        )
        # Create runtime parameters.
        runtime = util_models.RuntimeOptions()
        try:
            # Send a request
            client.send_message_to_globe_with_options(send_message_to_globe_request, runtime)
        except Exception as error:
            # print error message
            print(error.message)
            # Please click on the link below for diagnosis.
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)


if __name__ == '__main__':
    Sample.main(sys.argv[1:])

Special scenario: Configure the Advance API for file uploads

Some cloud products (such as Image Search and Visual Intelligence API) do not support direct file uploads through standard OpenAPI. Use the Advance API to pass a file stream instead. The file is temporarily stored in OSS (default region: cn-shanghai), then read by the product. The following example uses the DetectBodyCount API of Alibaba Cloud Visual Intelligence API (Face and Body):

Note

Temporary files stored in Alibaba Cloud OSS are cleaned up periodically.

  1. 1. Initialize the request client

    Set both region_id and the product endpoint. The region_id determines the OSS region for temporary file storage. If region_id does not match the product region, timeouts may occur.

    def create_client() -> facebody20191230Client:
        config = open_api_models.Config(
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your code execution environment.
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your code execution environment.
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        # The endpoint and regionId must be set to the same region.
        config.region_id = 'cn-shanghai'
        config.endpoint = 'facebody.cn-shanghai.aliyuncs.com'
        return facebody20191230Client(config)
  2. Create a request object

    Create an <OpenAPIName>AdvanceRequest object and pass the file stream as ImageURLObject.

    # Open the file as a binary stream.
    with open('<FILE_PATH>', "rb") as f:  # Replace with your file path.
         # Set request parameters.
         detect_body_count_advance_request = facebody_20191230_models.DetectBodyCountAdvanceRequest(
                   image_urlobject = f,
         )
  3. Send a request

    Call <apiName>Advance to send the request, where <apiName> is the OpenAPI name in lower camelCase.

    # Runtime configuration.
    runtime = util_models.RuntimeOptions()
    client = create_client()
    # Send the request.
    res = client.detect_body_count_advance(detect_body_count_advance_request, runtime)

Click to view the complete code example

import os

from alibabacloud_facebody20191230 import models as facebody_20191230_models
from alibabacloud_facebody20191230.client import Client as facebody20191230Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> facebody20191230Client:
        config = open_api_models.Config(
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your code execution environment.
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your code execution environment.
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        config.region_id = 'cn-shanghai'
        return facebody20191230Client(config)

    @staticmethod
    def main() -> None:
        client = Sample.create_client()
        # Open the file as a binary stream.
        with open('<FILE_PATH>', "rb") as f:  # Replace <FILE_PATH> with your file path.
            # Set request parameters.
            detect_body_count_advance_request = facebody_20191230_models.DetectBodyCountAdvanceRequest(
                image_urlobject=f,
            )
            runtime = util_models.RuntimeOptions()
            try:
                # Send the request.
                res = client.detect_body_count_advance(detect_body_count_advance_request, runtime)
                print(res)
            except Exception as error:
                # This is for printing and demonstration purposes only. Handle exceptions with care and do not ignore them in your project.
                print(error)


if __name__ == '__main__':
    Sample.main()

FAQ

  1. An OpenAPI call reports the error "You are not authorized to perform this operation".

    Cause and solution

    Cause: The RAM user associated with your AccessKey does not have permission to call this API.

    Solution: Grant the required OpenAPI permissions to the RAM user. Manage RAM user permissions.

    For example, if calling the or SendMessageToGlobe operation returns this error, create a custom permission policy like the following and attach it to the RAM user.

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendMessageToGlobe",
          "Resource": "*"
        }
      ]
    }
  2. An OpenAPI call reports an "SDK.EndpointResolvingError" related to the Endpoint.

    Cause and solution

    Cause: The specified endpoint is not supported by this API.

    Solution: Update the endpoint to a supported value and retry. Endpoint configuration.

  3. An OpenAPI call reports an `AttributeError: 'AttributeError' object has no attribute 'message'` or `KeyError: 'ALIBABA_CLOUD_ACCESS_KEY_ID'` error related to the AccessKey.

    Cause and solution

    Cause: Your AccessKey was not passed correctly.

    Solution: Verify that the AccessKey is passed correctly when initializing the client. os.environ("XXX") reads the value of XXX from environment variables.

Additional SDK error solutions: FAQ.