Alibaba Cloud SDK V1.0 for Python supports generic API calls, which let you call any API operation by installing only the core library, without service-specific SDKs.
Benefits
-
Lightweight: Call any API operation by installing only
aliyun-python-sdk-core. No service-specific SDKs required. -
Fast iteration: Call the latest API operations immediately, even when the service-specific SDK is unavailable or outdated.
Generic calls and specialized calls.
Usage notes
Before making a generic call, obtain the required API metadata, including the API version, request URL, and parameter type.
Install the core library
Run the following command to install the core library:
pip install aliyun-python-sdk-core
Call an API operation
Initialize a request client
Use the client module in aliyunsdkcore to create a client that calls API operations. This example uses an AccessKey pair. Other credential types are available in Manage access credentials.
To prevent AccessKey leaks, store your AccessKey pair in environment variables. Configure environment variables in Linux, macOS, and Windows.
import os
from aliyunsdkcore.client import AcsClient
# Use an AccessKey pair to directly initialize the request client.
client = AcsClient(
os.environ['ALIYUN_ACCESS_KEY_ID'],
os.environ['ALIYUN_ACCESS_KEY_SECRET'],
region_id='cn-hangzhou',
# verify=False # Disable SSL certificate verification.
# proxy={'http': 'http://127.0.0.1:9898'}, # Configure a proxy.
# proxy={'https': 'http://<user>:<password>@127.0.0.1:8989'},
connect_timeout=10, # Configure a timeout period for connection requests.
timeout=15 # Configure a timeout period for read requests.
)
Configure request parameters
Use CommonRequest to set common and operation-specific parameters for the API operation. Common parameter details are in Advanced settings.
The request module converts API metadata (version, URL, and parameter type) into a valid HTTP request and returns the raw response. How parameters are passed depends on the API style.
Operation-specific parameters
The API metadata determines how each parameter is passed. For example, the DescribeInstanceStatus operation defines {"name":"RegionId","in":"query",...}}, where "in":"query" means RegionId must be passed in putQueryParameter.
|
Description |
How the parameter is passed |
|
|
dd_query_param(self, k, v) Note
Format for multiple key-value pairs: dd_query_param("key.1","value1"); add_query_param("key.2","value2");... |
|
|
add_body_params(self, k, v) Note
Convert non-string parameter values to JSON strings. |
|
Upload files |
set_content(self, content) Note
Set the |
# 2. Create a CommonRequest object and configure the basic information about and request parameters of the API operation.
request = CommonRequest()
# 2.1 Configure common request parameters.
request.set_domain('ecs-cn-hangzhou.aliyuncs.com') # The endpoint of the API.
request.set_version('2014-05-26') # The API version number.
request.set_action_name('DescribeInstanceStatus') # The name of the API operation. When you call an RPC-style API operation, you must configure set_action_name() to specify the name of the API operation.
request.set_method('POST') # The request method of the API operation.
request.set_protocol_type('HTTPS') # The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
# request.set_uri_pattern('/') # The resource path, which is required by ROA-style API operations. Do not configure this parameter for RPC-style API operations.
# 2.2 Configure operation-specific request parameters.
# Scenario 1: Specify the query parameters in add_query_param(self, k, v).
InstanceIds = [
"i-bp1axhql4dqXXXXXXXX",
"i-bp124uve8zqXXXXXXXX"
]
for depth1 in range(len(InstanceIds)):
request.add_query_param('InstanceId.' + str(depth1 + 1), InstanceIds[depth1])
request.add_query_param('PageNumber', '1')
request.add_query_param('PageSize', '30')
# Scenario 2: Specify the body parameters in add_body_params(self, k, v).
# request.add_body_params('key1', 'value1')
# request.add_body_params('key2', 'value2')
# request.add_body_params('key3', 'value3')
# Scenario 3: Use set_content(self, content) to upload files, and set content to a byte array.
# file_path = "<FILE_PATH>" # Replace <FILE_PATH> with the actual file path.
# with open(file_path, 'rb') as file:
# Read the image content as a byte array.
# ByteArray = file.read()
# request.set_content(ByteArray)
Send the request
Call do_action_with_exception on the client with the CommonRequest instance.
# Initiate a request.
response = client.do_action_with_exception(request)
# If the response is of the byte type, the request ID and response parameters are returned.
print(f"response:\n{response}")
# Parse the response in JSON format.
response_json = json.loads(response.decode('utf-8')) # Convert the response to a Python dictionary.
print("RequestId:", response_json["RequestId"]) # The request ID.
Examples
Example: Call an RPC-style API operation
Call the DescribeInstanceStatus operation of Elastic Compute Service (ECS) with an RPC-style generic call.
import os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
class Sample:
@staticmethod
def main():
# Use an AccessKey pair to directly initialize the request client.
client = AcsClient(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
'cn-hangzhou')
# Create a request object.
request = CommonRequest()
request.set_domain('ecs-cn-hangzhou.aliyuncs.com') # The endpoint of the API.
request.set_version('2014-05-26') # The API version number.
request.set_action_name('DescribeRegions') # The name of the API operation. When you call an RPC-style API operation, you must configure set_action_name() to specify the name of the API operation.
request.set_method('POST') # The request method of the API operation.
request.set_protocol_type('HTTPS') # The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
InstanceIds = [
"i-bp1axhql4dqXXXXXXXX",
"i-bp124uve8zqXXXXXXXX"
]
for depth1 in range(len(InstanceIds)):
request.add_query_param('InstanceId.' + str(depth1 + 1), InstanceIds[depth1])
request.add_query_param('PageNumber', '1')
request.add_query_param('PageSize', '30')
# Initiate a request and handle the response.
response = client.do_action_with_exception(request)
print(response)
if __name__ == '__main__':
Sample.main()
Example: Call a RESTful-style (ROA-style) API operation
Call the DescribeClustersV1 operation of Container Service for Kubernetes (ACK) with a RESTful-style (ROA) generic call.
import os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
class Sample:
@staticmethod
def main():
# Use an AccessKey pair to directly initialize the request client.
client = AcsClient(
os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
'cn-hangzhou')
# Create a request object.
request = CommonRequest()
request.set_domain('cs.aliyuncs.com') # The endpoint of the API operation.
request.set_version('2015-12-15') # The API version number.
request.set_uri_pattern(
f'/api/v1/clusters') # The URL of the API operation. When you call an ROA-style API operation, you must configure set_uri_pattern() to specify a complete URL of the API operation. You can obtain the URL of an API operation from the API metadata.
request.set_method('GET') # The request method of the API operation.
request.add_query_param('name', 'cluster-demo') # Configure the request parameters.
# Initiate a request and handle the response.
response = client.do_action_with_exception(request)
print(response)
if __name__ == '__main__':
Sample.main()
FAQ
-
What can I do if the "Error:MissingParameter The input parameter "AccessKeyId" that is mandatory for processing this request is not supplied" error message is returned?
Cause: The AccessKey pair is not correctly configured.
Solutions:
-
Check whether the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set.
Linux/macOS
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRETWindows
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%If a valid AccessKey pair is returned, the environment variables are properly configured. If no valid AccessKey pair is returned, reconfigure the environment variables. Configure environment variables in Linux, macOS, and Windows.
-
Check for errors related to the AccessKey pair in the code.
Sample error request:
AccessKeyId = os.environ['yourAccessKeyID'], AccessKeySecret = os.environ['yourAccessKeySecret']NoteThe error occurs because the strings passed to os.environ are literal key names, not credentials. Set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as environment variables so os.environ reads the correct values.
Sample success request:
os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
-
-
What can I do if the "aliyunsdkcore.acs_exception.exceptions.ServerException: HTTP Status: 400 Error:MissingParameter The input parameter "Timestamp" that is mandatory for processing this request is not supplied" error message is returned?
Cause: uri_pattern is set for an RPC-style operation.
Solution: Remove uri_pattern from the request parameters.