All Products
Search
Document Center

Alibaba Cloud SDK:Generic calls

Last Updated:Aug 28, 2025

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

Characteristic

Lightweight: You can use Alibaba Cloud SDK V2.0 for Python to call API operations by installing only the core library of Alibaba Cloud SDK, without the need to install the SDK of each service.

Easy to use: You only need to create common request parameters and use a common client to initiate requests. The responses are returned in common formats.

For more information, see Generic calls and specialized calls.

Usage notes

Before you make a generic call, we recommend that you view the metadata of the API operation to obtain the API style, request parameters, and URL.

Install the core library of Alibaba Cloud SDK

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

pip install alibabacloud-tea-openapi

Call an API operation

1. Initialize the request client

Initialize the request client by creating a Client class from the client module in the alibabacloud_tea_openapi package. Use this client to make OpenAPI calls. You can also use the Credentials tool when you initialize the client. For more information about the Credentials tool, see Manage access credentials.

Important

The client instance is thread-safe. In your application, use the singleton pattern to create the client. This ensures that only one client instance is initialized for the same credential and endpoint during the application lifecycle.

import os

from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_openapi.client import Client as OpenApiClient

# Obtain the AccessKey pair from environment variables.
config = open_api_models.Config(
  access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
  access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# Set the service endpoint.
config.endpoint = f'ecs-cn-hangzhou.aliyuncs.com'
# config.protocol = 'HTTPS' # Send requests over HTTPS.
# config.http_proxy = 'http://127.0.0.1:9898'
# config.https_proxy='http://user:password@127.0.0.1:8989'
# config.read_timeout = 10000,  # Read timeout period in milliseconds (ms).
# config.connect_timeout = 5000  # Connection timeout period in milliseconds (ms).
client = OpenApiClient(config)


# Use the Credentials tool.
# crendconfig = credentialConfig()
# crendconfig.type = 'access_key'
# crendconfig.access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
# crendconfig.access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
# 
# credentialsClient = CredClient(crendconfig)
# config = open_api_models.Config()
# config.credential = credentialsClient
# config.endpoint = f'ecs.cn-hangzhou.aliyuncs.com'
# client = OpenApiClient(config)

2. Configure OpenAPI information

Use the Params class from the models module in the alibabacloud_tea_openapi package to configure basic OpenAPI information, such as the API style, API version, and request method. The following example shows how to call the DescribeInstanceTypeFamilies operation:

params = open_api_models.Params(
  style='RPC',  # API style: RPC or ROA.
  version='2014-05-26',  # API version number.
  action='DescribeInstanceTypeFamilies',  # API name.
  method='POST',  # Request method.
  pathname='/',  # API resource path. The default path for RPC APIs is "/". For ROA APIs, get the resource path from data.path in the OpenAPI metadata.
  protocol='HTTPS',  # Request protocol: HTTPS or HTTP. We recommend that you use HTTPS.
  auth_type='AK',  # Authentication type. The default value is used. If the OpenAPI supports anonymous requests, you can pass Anonymous to make an anonymous request.
  req_body_type='json',  # Request body type. Supported types are byte, json, and formData.
  body_type='json'  # Response data format. json is supported.
)

3. Configure request parameters

Use the OpenApiRequest class from the models module in the alibabacloud_tea_openapi package to configure request parameters. You can pass parameters through a query, body, or stream. Select a method based on the information in the metadata. For example, the RegionId request parameter of the DescribeInstanceTypeFamilies operation is specified as {"name":"RegionId","in":"query",...}} in the metadata. "in":"query" indicates that RegionId is passed as a query parameter.

How the parameter is passed

Description

query

If the request parameter shows "in":"query", pass the parameter through a query.

body

If the request parameter shows "in":"body" or "in": "formData", pass the parameter in the body. When you pass parameters in the request body, set the value of reqBodyType based on the body type.

stream

To upload files, you can pass file streams by configuring the Stream parameter.

from alibabacloud_openapi_util.client import Client as OpenApiUtilClient

# Scenario 1: Set query parameters.
query = {'RegionId': 'cn-hangzhou'}
# Create an API request object.
request = open_api_models.OpenApiRequest(
  query=OpenApiUtilClient.query(query),
)

# Scenario 2: Set body parameters. The value of reqBodyType is json.
# body = {
#  'param1': 'value1'
# }
# Create an API request object.
# request = open_api_models.OpenApiRequest(
#     body=OpenApiUtilClient.query(body),
# )

# Scenario 3: Use a stream parameter to pass a file stream.
# Create an API request object.
# request = open_api_models.OpenApiRequest(
#     stream='<FILE_STREAM>', # Replace <FILE_STREAM> with the actual file stream.
# )

# Scenario 4: Set body parameters. The value of reqBodyType is formData.
# form_data = {
#  'param1': 'value1'
# }
# Create an API request object.
# request = open_api_models.OpenApiRequest(
#     body=form_data,
# )
        

4. Send the request

Use the client created in Step 1 to call call_api for a synchronous request or call_api_async for an asynchronous request. You can also set runtime parameters for the current request, such as timeout and proxy configurations. For more information, see Advanced configurations.

from alibabacloud_tea_util import models as util_models

# Runtime configurations, which take effect only for the current request.
runtime = util_models.RuntimeOptions(
  # ignore_ssl=True  # Ignores SSL certificate verification. Verification is enabled by default.
  # autoretry=True,  # Specifies whether to enable retries. Default: disabled. 
  # max_attempts=3  # Number of retries. Default: 3.
)
# Synchronous call.
response = client.call_api(params, request, runtime)
# Asynchronous call.
# response = await client.call_api_async(params, request, runtime)

# The return value is a dict. You can get three types of data from the result: body, headers, and statusCode (the HTTP status code).
print(response['body'])

Sample code

Example: Call an RPC-style API operation

In this example, the DescribeInstanceTypeFamilies operation of Elastic Compute Service (ECS) is called to show how to make a generic call of an operation.

import os

from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient


class Sample:
  @staticmethod
  def main():
    # Obtain the AccessKey pair from environment variables.
    config = open_api_models.Config(
      access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
    # Set the service endpoint.
    config.endpoint = f'ecs-cn-hangzhou.aliyuncs.com'
    client = OpenApiClient(config)
    params = open_api_models.Params(
      style='RPC',  # API style.
      version='2014-05-26',  # API version number.
      action='DescribeInstanceTypeFamilies',  # API name.
      method='POST',  # Request method.
      pathname='/',  # API PATH. The default path for RPC APIs is "/".
      protocol='HTTPS',  # API protocol.
      auth_type='AK',
      req_body_type='json',  # Request body content format.
      body_type='json'  # Response body content format.
    )

    query = {'RegionId': 'cn-hangzhou'}
    # Create an API request object.
    request = open_api_models.OpenApiRequest(
      query=OpenApiUtilClient.query(query),
    )
    # Create a runtime options object.
    runtime = util_models.RuntimeOptions()
    # Call the API and print the response.
    response = client.call_api(params, request, runtime)
    # The return value is a Map. You can get three types of data from the Map: body, headers, and statusCode (the HTTP status code).
    print(response)

  @staticmethod
  async def main_async():
    """
        The asynchronous main function, which shows how to call an Alibaba Cloud API asynchronously.
        """
    # Obtain the AccessKey pair from environment variables.
    config = open_api_models.Config(
      access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
    # Set the service endpoint.
    config.endpoint = f'ecs-cn-hangzhou.aliyuncs.com'
    client = OpenApiClient(config)
    params = open_api_models.Params(
      style='RPC',  # API style.
      version='2014-05-26',  # API version number.
      action='DescribeInstanceTypeFamilies',  # API name.
      method='POST',  # Request method.
      pathname='/',  # API PATH.
      protocol='HTTPS',  # API protocol.
      auth_type='AK',
      req_body_type='json',  # Request body content format.
      body_type='json'  # Response body content format.
    )

    query = {'RegionId': 'cn-hangzhou'}
    # Create an API request object.
    request = open_api_models.OpenApiRequest(
      query=OpenApiUtilClient.query(query),
    )
    # Create a runtime options object.
    runtime = util_models.RuntimeOptions()
    # Make an asynchronous API call.
    await client.call_api_async(params, request, runtime)


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 alibabacloud_openapi_util.client import Client as OpenApiUtilClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_util import models as util_models


class Sample:
  @staticmethod
  def main() -> None:
    # Obtain the AccessKey ID and AccessKey secret from environment variables.
    config = open_api_models.Config(
      access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
    config.endpoint = f'cs.cn-qingdao.aliyuncs.com'
    client = OpenApiClient(config)
    params = open_api_models.Params(
      # API name.
      action='DescribeClustersV1',
      # API version.
      version='2015-12-15',
      # API protocol.
      protocol='HTTPS',
      # API HTTP method.
      method='GET',
      auth_type='AK',
      style='ROA',
      # API PATH. For ROA APIs, get the resource path from data.path in the OpenAPI metadata.
      pathname=f'/api/v1/clusters',
      # Request body content format.
      req_body_type='json',
      # Response body content format.
      body_type='json'
    )
    # query params
    queries = {'name': 'cluster-demo'}
    request = open_api_models.OpenApiRequest(
      query=OpenApiUtilClient.query(queries)
    )
    # runtime options
    runtime = util_models.RuntimeOptions()
    # The return value is a Map. You can get three types of data from the Map: the response body, response headers, and the HTTP status code.
    response = client.call_api(params, request, runtime)
    print(response)

  @staticmethod
  async def main_async() -> None:
    # Obtain the AccessKey ID and AccessKey secret from environment variables.
    config = open_api_models.Config(
      access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
    config.endpoint = f'cs.cn-qingdao.aliyuncs.com'
    client = OpenApiClient(config)
    params = open_api_models.Params(
      # API name.
      action='DescribeClustersV1',
      # API version.
      version='2015-12-15',
      # API protocol.
      protocol='HTTPS',
      # API HTTP method.
      method='GET',
      auth_type='AK',
      style='ROA',
      # API PATH.
      pathname=f'/api/v1/clusters',
      # Request body content format.
      req_body_type='json',
      # Response body content format.
      body_type='json'
    )
    # query params
    queries = {'name': 'cluster-demo'}
    request = open_api_models.OpenApiRequest(
      query=OpenApiUtilClient.query(queries)
    )
    # runtime options
    runtime = util_models.RuntimeOptions()
    # The return value is a Map. You can get three types of data from the Map: the response body, response headers, and the HTTP status code.
    await client.call_api_async(params, request, runtime)


if __name__ == '__main__':
  Sample.main()