All Products
Search
Document Center

Alibaba Cloud SDK:Generic calls

Last Updated:Jul 07, 2025

Alibaba Cloud SDK V1.0 for Python supports generic API calls. This topic describes how to make generic calls by using Alibaba Cloud SDK V1.0 for Python.

Characteristics

  1. Lightweight: You can use Alibaba Cloud SDK V1.0 for Python to call all API operations by installing only aliyun-python-sdk-core, without the need to install the SDK of each service.

  2. Fast iteration and compatibility: If a cloud service does not provide an SDK, or the SDK is not updated for the latest API operations, you can make generic calls. This way, you can call the latest API operations without the need to wait for SDK updates.

For more information, see Generic calls and specialized calls.

Usage notes

Before you make a generic call, manually obtain and specify the required metadata, including the API version, request URL, and parameter type. For more information, see API metadata.

Install the core library of Alibaba Cloud SDK V1.0 for Python

Run the following command on your terminal to install the core library of Alibaba Cloud SDK V1.0 for Python:

pip install aliyun-python-sdk-core

Call an API operation

Initialize a request client

In the aliyunsdkcore package, create a client module to initialize the request client, and use the client to call API operations. In this example, an AccessKey pair is used to initialize the request client. For more information, see Manage access credentials.

Note

To prevent AccessKey leaks, you can record the AccessKey pair in environment variables. For more information, see 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 the API operation information and request parameters

Use CommonRequest to configure the common request parameters and operation-specific parameters for the API operation. For more information about the common request parameters, see Advanced settings.

Note

The request module is used to convert the API metadata, such as the version number, URL, and parameter type, to a valid HTTP request through a standard request configuration process, and then return the original response data. How parameters are passed are determined by the API style and design.

Operation-specific parameters

How a request parameter is passed is determined by the metadata of the API operation. For example, the DescribeInstanceStatus API operation is defined as {"name":"RegionId","in":"query",...}} in the metadata. In this case, "in":"query" indicates that the region ID (RegionId) must be passed in putQueryParameter.

Description

How the parameter is passed

"in":"query"

dd_query_param(self, k, v)

Note

To specify a set of key-values pairs, specify them in the following format: dd_query_param("key.1","value1");

add_query_param("key.2","value2");...

"in":"body" or "in": "formData"

add_body_params(self, k, v)

Note

If the request parameter is not of the string type, you must convert the parameter value to a JSON string.

Upload files

set_content(self, content)

Note

Set the content parameter to a byte array.

# 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)

Initiate a request

Use the client to call the do_action_with_exception function. Use the CommonRequest instance to specify the request parameters.

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

Sample code

Example: Call an RPC-style API operation

The following example shows how to call the DescribeInstanceStatus API operation of Elastic Compute Service (ECS).

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

In this example, the DescribeClustersV1 operation of Container Service for Kubernetes (ACK) is called to show how to make a generic call of an operation.

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

  1. 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:

    1. Run the following commands to check whether the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.

      Linux/macOS

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

      Windows

      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 AccessKey pair or an invalid AccessKey pair is returned, configure the environment variables as required. For more information, see Configure environment variables in Linux, macOS, and Windows.

    2. Check for errors related to the AccessKey pair in the code.

      Sample error request:

      AccessKeyId = os.environ['yourAccessKeyID'],
      AccessKeySecret = os.environ['yourAccessKeySecret']
      Note

      In the preceding sample error request, the input values of os.environ are used as the AccessKey pair. However, this function is used to read values from the environment variables. After you specify the environment variable names as ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET on your machine, os.environ can read the values from the environment variables.

      Sample success request:

      os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], 
      os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  2. 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: The uri_pattern parameter is configured in the common request parameters of the RPC-style API operation.

    Solution: Remove the uri_pattern parameter from the common request parameters.