All Products
Search
Document Center

AnalyticDB:Use AnalyticDB for PostgreSQL SDK for Python

Last Updated:Mar 28, 2026

This guide shows how to call the DescribeDBInstances operation using the Alibaba Cloud SDK for Python. By the end, you'll have a working Python script that lists your AnalyticDB for PostgreSQL instances and a verified SDK setup you can build on.

Prerequisites

Before you begin, ensure that you have:

  • An Alibaba Cloud account with at least one AnalyticDB for PostgreSQL instance

  • Python 3 installed (python --version to check; download from python.org if needed)

  • Familiarity with running commands in a terminal

How it works

All requests to the AnalyticDB for PostgreSQL API are authenticated using a Resource Access Management (RAM) user's AccessKey. The SDK reads credentials from environment variables and sends signed API requests to the service endpoint.

The setup has three parts:

  1. Create a RAM user with the right permissions and save its AccessKey.

  2. Set the AccessKey as environment variables and install the SDK packages.

  3. Run the script — the SDK handles authentication, request signing, and response parsing.

Step 1: Create a RAM user and grant permissions

If you already have a RAM user with AnalyticDB for PostgreSQL permissions, skip to Step 2.

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

  2. Set Logon Name to adbpg-openapi-operator and select Using permanent AccessKey to access for Access Mode. Click OK.

  3. Save the AccessKey ID and AccessKey secret shown after creation. You won't be able to retrieve the secret again.

  4. On the Users page, find the user you created and click Add Permissions in the Actions column.

  5. In the Policy section, search for AliyunGPDB and select AliyunGPDBReadOnlyAccess. Click OK.

AliyunGPDBReadOnlyAccess grants read-only access to query instances. To also modify instances, select AliyunGPDBFullAccess instead. To define a custom set of permissions, see Create custom policies.

Step 2: Set up your environment

Set environment variables

Store your AccessKey in environment variables rather than hardcoding it in scripts.

Linux or macOS:

export ALIBABA_CLOUD_ACCESS_KEY_ID=<ACCESS_KEY_ID>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET>

Windows:

Add ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET to your system environment variables, set their values, and restart your system.

Replace the placeholders with your actual values:

PlaceholderDescription
<ACCESS_KEY_ID>The AccessKey ID saved in Step 1
<ACCESS_KEY_SECRET>The AccessKey secret saved in Step 1

Install dependencies

The SDK is split across three packages:

pip install alibabacloud_credentials      # Credential management and authentication
pip install alibabacloud_gpdb20160503     # AnalyticDB for PostgreSQL API client
pip install alibabacloud_tea_console      # Console logging utilities

Step 3: Call the DescribeDBInstances operation

The following self-contained script calls DescribeDBInstances and prints the response. Copy it, replace the region_id value, and run it directly.

import os
import json
from alibabacloud_gpdb20160503.client import Client as gpdb20160503Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models
from alibabacloud_tea_util import models as util_models

def create_client() -> gpdb20160503Client:
    # Read credentials from environment variables — never hardcode AccessKey values
    config = open_api_models.Config(
        access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
    # Set the endpoint for the target region
    config.endpoint = 'gpdb.aliyuncs.com'
    return gpdb20160503Client(config)

def main():
    client = create_client()

    # Build the request — RegionId filters instances to a specific region
    request = gpdb_20160503_models.DescribeDBInstancesRequest(
        region_id='cn-hangzhou'  # Replace with your target region
    )
    runtime = util_models.RuntimeOptions()

    try:
        response = client.describe_db_instances_with_options(request, runtime)
        # Print the full response for verification
        print(json.dumps(response.body.to_map(), indent=2, default=str))
    except Exception as err:
        # Check the error type to diagnose the issue:
        # - InvalidAccessKeyId: the AccessKey ID is incorrect or not set
        # - Forbidden: the RAM user lacks the required permission
        # - SignatureDoesNotMatch: the AccessKey secret is incorrect
        print(f"Request failed: {err}")
        raise

if __name__ == '__main__':
    main()

Run the script:

python sample.py

Verify the result

A successful call returns HTTP 200 with a list of instances. The response looks similar to:

{
  "Items": {
    "DBCluster": [
      {
        "CreateTime": "2023-07-31T07:09:32Z",
        "DBInstanceCategory": "Basic",
        "DBInstanceDescription": "gp-bp1j20nrgf91****",
        "DBInstanceId": "gp-bp1j20nrgf91****",
        "DBInstanceMode": "StorageElastic",
        "DBInstanceNetType": "2",
        "DBInstanceStatus": "Running",
        "Engine": "gpdb",
        "EngineVersion": "6.0",
        "ExpireTime": "2023-08-31T16:00:00Z",
        "InstanceDeployType": "cluster",
        "InstanceNetworkType": "VPC",
        "LockMode": "Unlock",
        "LockReason": "0",
        "MasterNodeNum": 1,
        "PayType": "Prepaid",
        "RegionId": "cn-hangzhou",
        "ResourceGroupId": "rg-acfmz7u4zzr****",
        "SegNodeNum": "2",
        "StorageSize": "50",
        "StorageType": "cloud_essd",
        "Tags": {"Tag": []},
        "VSwitchId": "vsw-bp1sxxsodv28ey5****",
        "VpcId": "vpc-bp1ov7as4yvz4kxei****",
        "ZoneId": "cn-hangzhou-j"
      }
    ]
  },
  "PageNumber": 1,
  "PageRecordCount": 1,
  "TotalRecordCount": 1,
  "RequestId": "22996ADD-A917-5F47-AA7E-2D9A08AF1AC2"
}

If the response is empty (TotalRecordCount: 0), no instances exist in the specified region — the SDK itself is working correctly. Try a different region ID.

What's next