Initialize an SDK client and send API requests

Updated at:
Copy as MD

Set up the Alibaba Cloud SDK V1.0 for Python and make your first API call in a few steps.

Prerequisites

Before you begin, ensure that you have:

Install the SDK

All Alibaba Cloud services share a single Core SDK in SDK V1.0 for Python. Install it with pip:

pip install aliyun-python-sdk-core

Initialize an SDK client

The Core SDK provides an AcsClient that handles all API requests. Create a client by passing your credentials and target region:

import os

from aliyunsdkcore.client import AcsClient

client = AcsClient(
    os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),     # AccessKey ID from environment variable
    os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), # AccessKey secret from environment variable
    '<region_id>'  # Region ID, for example, cn-hangzhou
)
Note

Store credentials in environment variables, not in source code. Hardcoded keys are exposed if the code is shared or committed to version control.

Send API requests

Each Alibaba Cloud service SDK provides request and response objects for its API operations. Import the request class for the operation you want to call, set any parameters, and pass the request to do_action_with_exception.

The following example calls the DescribeRegions operation of Elastic Compute Service (ECS) and prints the response:

import os

from aliyunsdkcore.client import AcsClient
from aliyunsdkecs.request.v20140526.DescribeRegionsRequest import DescribeRegionsRequest

client = AcsClient(
    os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    '<region_id>'
)

# Build the request
request = DescribeRegionsRequest()

# Send the request and print the response
response = client.do_action_with_exception(request)
print(str(response, encoding='utf-8'))

Install the ECS service SDK before running this example:

pip install aliyun-python-sdk-ecs

For the full list of request and response parameters, see the ECS API reference.

References

For credential management options beyond environment variables, see Manage access credentials.