Python SDK examples

Updated at:

This topic uses the Python SDK V2.0 as an example to demonstrate how to call Cloud Monitor 2.0 (cms20240330) OpenAPI operations. The calling method is similar for other operations. You only need to replace the request and response types and fields.

Prerequisite

Python 3.7 or later.

Installation

Install via pip:

pip install alibabacloud_cms20240330==10.0.0

Source code repository: alibabacloud-python-sdk/cms-20240330.

Configure access credentials

We recommend that you use a more secure method that does not require an AccessKey pair for your project code. For more information about credential configuration, see Manage access credentials. The simplest approach is to configure environment variables:

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

CredentialClient() searches for credentials in the order defined by the default credential chain.

Complete code example

The following example calls the GetCmsService operation to query the activation status of a Cloud Monitor 2.0 service for a specific product:

# -*- coding: utf-8 -*-
import os
import sys
import json
from typing import List

from alibabacloud_cms20240330.client import Client as Cms20240330Client
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_cms20240330 import models as cms_20240330_models
from alibabacloud_tea_util import models as util_models


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Cms20240330Client:
        """
        Use credentials to initialize the client.
        """
        # For production code, we recommend using a more secure method that does not require an AccessKey pair. 
        credential = CredentialClient()
        config = open_api_models.Config(credential=credential)
        # For more information about the endpoint, see https://api.aliyun.com/product/Cms.
        config.endpoint = 'metrics.cn-hangzhou.aliyuncs.com'
        return Cms20240330Client(config)

    @staticmethod
    def main(args: List[str]) -> None:
        client = Sample.create_client()
        request = cms_20240330_models.GetCmsServiceRequest(
            product='your_value',
            service='your_value',
        )
        headers = {}
        try:
            resp = client.get_cms_service_with_options(request, headers, util_models.RuntimeOptions())
            print(json.dumps(resp, default=str, indent=2))
        except Exception as error:
            # The error message.
            print(error.message)
            # The URL for troubleshooting.
            print(error.data.get("Recommend"))


if __name__ == '__main__':
    Sample.main(sys.argv[1:])

Procedure

The code works as follows

  1. Initialize the Config object alibabacloud_tea_openapi.Config. The Config object stores the credential, endpoint, and other configurations. The Endpoint is metrics.cn-hangzhou.aliyuncs.com as shown in the example.

    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_credentials.client import Client as CredentialClient
    
    credential = CredentialClient()
    config = open_api_models.Config(credential=credential)
    config.endpoint = 'metrics.cn-hangzhou.aliyuncs.com'
  2. Instantiate the client:

    from alibabacloud_cms20240330.client import Client as Cms20240330Client
    from alibabacloud_cms20240330 import models as cms_20240330_models
    
    client = Cms20240330Client(config)
  3. Create the Request object for the API operation:

    request = cms_20240330_models.GetCmsServiceRequest()
  4. Set request parameters:

    request.product = 'your_value'
    request.service = 'your_value'
  5. Call the API operation:

    response = client.get_cms_service(request)
    print(response)
  6. Read return values from the response, for example:

    request_id = response.body.request_id
    print(request_id)
  7. Use try...except... to handle errors:

    try:
        response = client.get_cms_service(request)
    except Exception as e:
        print(e)

For more API operations and sample code, see SDK examples on the OpenAPI portal.