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
-
Log on to SDK Center and select the product whose APIs you want to call, such as Short Message Service (SMS).
-
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).

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
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=yourAccessKeyIDConfigure the AccessKey secret and press Enter.
# Replace yourAccessKeySecret with your AccessKey secret. export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecretVerify the configuration.
Run the
echo $ALIBABA_CLOUD_ACCESS_KEY_IDcommand. 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%andecho %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 /MThe
/Mparameter 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%andecho %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.
-
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.
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.
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.
Always handle exceptions properly — propagate, log, or recover — to ensure system stability.
Click to view the complete code example
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):
Temporary files stored in Alibaba Cloud OSS are cleaned up periodically.
-
1. Initialize the request client
Set both
region_idand the productendpoint. Theregion_iddetermines the OSS region for temporary file storage. Ifregion_iddoes 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) -
Create a request object
Create an
<OpenAPIName>AdvanceRequestobject and pass the file stream asImageURLObject.# 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, ) -
Send a request
Call
<apiName>Advanceto 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)
FAQ
-
An OpenAPI call reports the error "You are not authorized to perform this operation".
-
An OpenAPI call reports an "SDK.EndpointResolvingError" related to the Endpoint.
-
An OpenAPI call reports an `AttributeError: 'AttributeError' object has no attribute 'message'` or `KeyError: 'ALIBABA_CLOUD_ACCESS_KEY_ID'` error related to the AccessKey.
Additional SDK error solutions: FAQ.