All Products
Search
Document Center

ApsaraDB RDS:Python SDK example

Last Updated:Feb 27, 2026

This topic describes how to install and use Alibaba Cloud SDK for Python to call the DescribeDBInstances operation to query your ApsaraDB RDS instances.

Prerequisites

Before you begin, make sure that you have:

  • Python 3 installed (download)

  • pip (included with Python 3.4+)

  • An Alibaba Cloud account with an AccessKey pair

Step 1: Create a RAM user and grant permissions

Skip this step if you already have a Resource Access Management (RAM) user with the required permissions.

Create the RAM user

  1. Log on to the RAM console and go to the Users page.

  2. Click Create User.

  3. Set Logon Name to rds-openapi-operator and select Using permanent AccessKey to access for Access Mode.

  4. Click OK. Save the AccessKey ID and AccessKey secret. The AccessKey secret is displayed only once.

Grant permissions

  1. On the Users page, find the RAM user and click Add Permissions in the Actions column.

  2. Search for AliyunRDS and select the AliyunRDSReadOnlyAccess policy.

    Note

    The AliyunRDSReadOnlyAccess policy grants read-only access to RDS. For full management permissions, select AliyunRDSFullAccess instead. For fine-grained access control, create a custom policy.

  3. Click Grant permissions.

Step 2: Configure credentials

Set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to your AccessKey pair.

Linux or macOS

export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>

Windows

Add ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as system environment variables with your AccessKey pair values, then restart the system.

Step 3: Install the SDK

pip install alibabacloud_rds20140815==5.0.1

Step 4: Write and run the code

Create a file named sample.py with the following code. This example calls the DescribeDBInstances operation to list RDS instances in the cn-beijing region. Replace cn-beijing with the region of your instances, such as ap-southeast-1.

import os
import sys
import json

from alibabacloud_rds20140815.client import Client
from alibabacloud_rds20140815.models import DescribeDBInstancesRequest
from alibabacloud_tea_openapi.models import Config


def create_client():
    """Create an ApsaraDB RDS client using environment variable credentials."""
    config = Config(
        access_key_id=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"),
        access_key_secret=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
        endpoint="rds.aliyuncs.com",
    )
    return Client(config)


def main():
    """Query RDS instances in the specified region."""
    client = create_client()
    request = DescribeDBInstancesRequest(region_id="cn-beijing")

    try:
        response = client.describe_dbinstances(request)
        print(json.dumps(response.body.to_map(), indent=4))
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

Run the code:

python sample.py

Alternative: Download sample code from OpenAPI Portal

To generate and download sample code with custom parameters:

  1. Open the DescribeDBInstances page on OpenAPI Portal.

  2. On the Parameters tab, set RegionId to cn-beijing or the region of your instances.

  3. On the SDK Sample Code tab, select Python and click Download Project.

  4. Extract the package and go to the alibabacloud_sample directory.

  5. Run the sample:

       python sample.py

Sample response

A successful response looks similar to:

{
    "Items": {
        "DBInstance": [
            {
                "ConnectionMode": "Standard",
                "ConnectionString": "rm-2zea24972vgw2****.mysql.rds.aliyuncs.com",
                "CreateTime": "2024-06-18T10:09:56Z",
                "DBInstanceClass": "mysql.n1e.small.1",
                "DBInstanceId": "rm-2zea24972vgw2****",
                "DBInstanceMemory": 1024,
                "DBInstanceNetType": "Intranet",
                "DBInstanceStatus": "Creating",
                "DBInstanceStorageType": "general_essd",
                "DBInstanceType": "Primary",
                "DeletionProtection": false,
                "Engine": "MySQL",
                "EngineVersion": "8.0",
                "ExpireTime": "2024-07-18T16:00:00Z",
                "InstanceNetworkType": "VPC",
                "LockMode": "Unlock",
                "MutriORsignle": false,
                "PayType": "Prepaid",
                "ReadOnlyDBInstanceIds": {
                    "ReadOnlyDBInstanceId": []
                },
                "RegionId": "cn-beijing",
                "ResourceGroupId": "rg-acfmz7u4zzr****",
                "TipsLevel": 0,
                "VSwitchId": "vsw-2zeyawzswr2lno0ys****",
                "VpcCloudInstanceId": "rm-2zea24972vgw2****-20240618180950",
                "VpcId": "vpc-2zeev9fov0chw8hjt****",
                "ZoneId": "cn-beijing-l"
            }
        ]
    },
    "NextToken": "o7PHCFqQhehg8NUW9EJ7Yw",
    "PageNumber": 1,
    "PageRecordCount": 1,
    "RequestId": "3BBF9A9B-E74C-5EF5-99BB-4F65B4B67499",
    "TotalRecordCount": 1
}

Next steps