Integrate the SDK
The Alibaba Cloud SDK simplifies development and feature integration when you call OpenAPI operations from your application. This topic describes the complete integration flow: install the SDK, configure access credentials, and use the SDK. It also covers the Advance API for file uploads and frequently asked questions.
Prerequisites
-
Python — Python 3.7 or later.
-
AccessKey pair — An AccessKey pair is required to call Alibaba Cloud OpenAPI. The Resource Access Management (RAM) user associated with the AccessKey pair must have the permissions to call the target API operations. Otherwise, calls fail with the "You are not authorized to perform this operation" error.
-
SDK packages — The main examples in this topic require the
alibabacloud_dysmsapi20170525,alibabacloud_tea_openapi, andalibabacloud_tea_utilpackages.
Install the SDK
SDK Center provides the SDK installation method for each product. To obtain and install the SDK:
-
Log on to SDK Center.
-
Select the product whose APIs you want to call, such as Short Message Service (SMS).
-
On the Installation page, select V2.0 for SDK Generation and Python for All Languages.
-
On the Getting Started tab, find the SDK installation method for Short Message Service (SMS) and install the SDK.
Configure access credentials
Calls to Alibaba Cloud OpenAPI usually require access credentials. Common credential types are AccessKey (AK) and Security Token Service (STS) tokens. To prevent credential leakage, a common practice is to store credentials in environment variables. For more information about security best practices, see Secure use of access credentials.
This topic uses an AccessKey pair as the example. The following example uses the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables:
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:
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
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%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.
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.
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
The standard call flow applies to most scenarios. Some cloud products do not support direct file uploads through standard OpenAPI operations. To upload files to these products, use the Advance API. See Upload files with the Advance API.
This topic uses the SendSms operation of Short Message Service (SMS) as an example. For the API reference of the SendSms operation, see SendSms.
Initialize the request client
All OpenAPI calls are made through the request client (Client) provided by the SDK. Initialize the request client before you call any OpenAPI operation. The request client supports multiple initialization methods. This example uses an AccessKey pair. For more initialization methods, see Manage access credentials.
-
Client objects are thread-safe. For example, you can safely share one Dysmsapi20170525Client instance in a multi-threaded environment. You do not need to create a separate instance for each thread.
-
Do not frequently create client objects. Frequent creation wastes resources and degrades performance. (Recommended) Use the singleton pattern to wrap the client, and make sure that only one client instance is initialized for the same access credentials and endpoint throughout the application lifecycle.
@staticmethod
def create_client() -> Dysmsapi20170525Client:
# Leaking project code may lead to the disclosure of your AccessKey and threaten the security of all resources in your account. The following sample code is for reference only.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
config.endpoint = f'dysmsapi.aliyuncs.com'
return Dysmsapi20170525Client(config)
Create a request object
To pass parameters when you call an OpenAPI operation, use the request object provided by the SDK. Request objects are named in the <API operation name>Request format. For more information about request parameters, see the corresponding API documentation. For the API documentation used in this example, see SendSms.
If an OpenAPI 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 a request object and set the input parameters.
send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
# Replace with the mobile phone number of the recipient.
phone_numbers='<YOUR_VALUE>',
# Replace with your SMS signature.
sign_name='<YOUR_VALUE>',
# Replace with the code of your SMS template.
template_code='<YOUR_VALUE>',
# Replace with the template parameters. The value must be a JSON string. Example: {"code":"1234","name":"1234","time":"1234"}
template_param='<YOUR_VALUE>'
)
Send the request
(Recommended) Call the <api_name>_with_options function to send the request, where <api_name> is the OpenAPI name in snake_case. The function takes two parameters: the request object created in the previous step and a runtime options object. The runtime options object configures request behavior, such as timeout settings and proxy settings. For more information, see Advanced Configurations.
The function returns a response object if the request succeeds. Print or log the response to verify the call result.
If an 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, you pass only the runtime options.
# Create runtime parameters.
runtime = util_models.RuntimeOptions()
client = create_client()
# Send the request.
send_sms_response = client.send_sms_with_options(send_sms_request, runtime)
Handle exceptions
The V2.0 Python SDK classifies exceptions into two main types:
-
TeaUnretryableException: thrown mainly due to network issues, after the network retries reach the maximum retry count.
-
TeaException: thrown mainly for service-side business errors.
For more information about exception handling, see Exception handling.
Take proper measures to handle exceptions, such as propagating exceptions, recording logs, and attempting recovery, to ensure the robustness and stability of your system.
Complete code example
The following example combines the preceding steps: initializing the request client, creating a request object, sending the request, and handling exceptions.
API call example
import os
import sys
from typing import List
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_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() -> Dysmsapi20170525Client:
# Leaking your project code may compromise your AccessKey and threaten the security of all resources in your account. The following sample code is for reference only.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
config.endpoint = f'dysmsapi.aliyuncs.com'
return Dysmsapi20170525Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = Sample.create_client()
send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
# Replace with the mobile phone number of the recipient.
phone_numbers='<YOUR_VALUE>',
# Replace with your SMS signature.
sign_name='<YOUR_VALUE>',
# Replace with the code of your SMS template.
template_code='<YOUR_VALUE>',
# Replace with the template parameters. The value must be a JSON string. Example: {"code":"1234","name":"1234","time":"1234"}
template_param='<YOUR_VALUE>'
)
runtime = util_models.RuntimeOptions()
try:
# Send the request.
send_sms_response = client.send_sms_with_options(send_sms_request, runtime)
# Print the API response to verify the result.
print(send_sms_response)
except Exception as error:
# For printing and demonstration purposes only. Handle exceptions with care and never ignore exceptions in your project.
# The error message.
error_message = getattr(error, 'message', str(error))
print(error_message)
# The diagnostic URL.
print(getattr(error, 'data', {}).get("Recommend"))
UtilClient.assert_as_string(error_message)
if __name__ == '__main__':
Sample.main(sys.argv[1:])
Upload files with the Advance API
Some cloud products, such as Image Search and Visual Intelligence API, do not support direct file uploads through the standard OpenAPI operations described in the official documentation. To upload files to these products, use the Advance API provided by the cloud product. The Advance API accepts a file stream object. Under the hood, the cloud product temporarily stores the uploaded file in Alibaba Cloud OSS. The default storage region is cn-shanghai. The cloud product reads the temporary file from OSS to provide the feature. The following example uses the DetectBodyCount API of the Face and Body service on Alibaba Cloud Visual Intelligence API.
Temporary files stored in Alibaba Cloud OSS are cleaned up periodically.
To initialize the request client
Set both region_id and the product endpoint when you initialize the request client. The region_id specifies the storage region of the temporary file in OSS. If region_id is not set, the product and OSS may reside in different regions, which may cause timeouts when you call the OpenAPI operation.
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)
To create a request object
Create an <OpenAPIName>AdvanceRequest request object to pass the file stream. The parameter name is fixed 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,
)
To send the request
Call the <apiName>Advance function 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)
The following example shows the complete code for uploading a file with the Advance API.
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'
config.endpoint = 'facebody.cn-shanghai.aliyuncs.com'
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
"You are not authorized to perform this operation"
Cause: The RAM user associated with your AccessKey pair does not have the permissions to call this API operation.
Solution: Grant the required OpenAPI permissions to the RAM user. For more information about how to grant permissions to a RAM user, see Manage RAM user permissions.
For example, the call of the SendSms operation returns this error if the RAM user lacks the corresponding permission. Create a custom permission policy like the following one and grant the corresponding permissions to the RAM user.
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": "dysms:SendSms",
"Resource": "*"
}
]
}
"SDK.EndpointResolvingError"
Cause: The OpenAPI operation that you call does not support the endpoint specified when you initialize the request client.
Solution: Check Endpoint configuration, update the endpoint to a supported value, and then call the OpenAPI operation again.
AttributeError or KeyError related to the AccessKey
An OpenAPI call reports AttributeError: 'AttributeError' object has no attribute 'message' or KeyError: 'ALIBABA_CLOUD_ACCESS_KEY_ID'.
Cause: The AccessKey pair is not passed correctly.
Solution: When you initialize the request client, check whether the AccessKey pair is passed correctly. Note that os.environ["XXX"] gets the value of XXX from environment variables.
For more solutions to errors that you encounter when you use the SDK, see FAQ.