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
Initialize a request client
Create the alibabacloud_tea_openapi.client
object to initialize a request client, and use the client to call the API operation. When you initialize a client, you can also use the Credentials tool. For more information about the Credentials tool, see Manage access credentials.
# 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']
)
# Specify the endpoint of the service.
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, # Configure a timeout period for read requests. Unit: milliseconds.
# config.connect_timeout = 5000 # Configure a timeout period for connection requests. Unit: milliseconds.
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)
Configure the information about the API operation
Use open_api_models.Params
to configure the basic information about the API operation, such as the API style, API version, and request method. In the following example, the DescribeInstanceTypeFamilies operation is called.
params = open_api_models.Params(
style='RPC', # The API style, such as remote procedure call (RPC) and resource-oriented architecture (ROA).
version='2014-05-26', # The version number of the API operation.
action='DescribeInstanceTypeFamilies', # The API operation.
method='POST', # The HTTP method of the API operation.
pathname='/', # The URL of the API operation. The default path of an RPC-style operation is /. You can obtain the URL of an ROA-style operation from the data.path parameter in the API metadata.
protocol='HTTPS', # The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
auth_type='AK', # The authentication type. Use the default type. If the operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request.
req_body_type='json', # The type of request body. Valid values: byte, json, and formData.
body_type='json' # The response format. JSON is supported.
)
Configure request parameters
Use open_api_models.OpenApiRequest
to configure the request parameters. You can pass the request parameters in a query string, a body, or a stream. Select a method to pass request parameters based on the metadata of the API operation. For example, the RegionId request parameter of the DescribeInstanceTypeFamilies
API operation is defined as {"name":"RegionId","in":"query",...}}
in the metadata. "in":"query"
indicates that the RegionId parameter is passed in a query string.
How the parameter is passed | Description |
query | If the metadata defines |
body | If the metadata defines |
stream | If you need to upload files, you can pass file streams by configuring the Stream parameter. |
# Scenario 1: Configure a query string.
query = {'RegionId': 'cn-hangzhou'}
# Create an API request.
request = open_api_models.OpenApiRequest(
query=OpenApiUtilClient.query(query),
)
# Scenario 2: Configure a body and set reqBodyType to json.
# body = {
# 'param1': 'value1'
# }
# Create an API request.
# request = open_api_models.OpenApiRequest(
# body=OpenApiUtilClient.query(body),
# )
# Scenario 3: Configure the Stream parameter to pass file streams.
# Create an API request.
# request = open_api_models.OpenApiRequest(
# stream='<FILE_STREAM>', # Replace <FILE_STREAM> with the file stream that you want to pass.
# )
# Scenario 4: Configure a request body and set reqBodyType to formData.
# form_data = {
# 'param1': 'value1'
# }
# Create an API request.
# request = open_api_models.OpenApiRequest(
# body=form_data,
# )
Initiate a request
Use the client
to call the call_api function for initiating a synchronous request or call the call_api_async function for initiating an asynchronous request. When you call an API operation, you can specify runtime parameters, such as timeout parameters and proxy parameters. For more information, see Advanced settings.
# Configure the runtime parameters.
runtime = util_models.RuntimeOptions(
# ignore_ssl=True # Disable certificate verification. By default, certificate verification is enabled.
# autoretry=True, # Specify whether to enable retries. By default, retries are disabled.
# max_attempts=3 # The maximum number of retries. Default value: 3.
)
# Make a synchronous call.
response = client.call_api(params, request, runtime)
# Make an asynchronous call.
# response = await client.call_api_async(params, request, runtime)
# The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
print(response)
Sample code
Example: Call an RPC-style API operation
In this example, the DescribeRegions operation of 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
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']
)
# Specify the endpoint of the service.
config.endpoint = f'ecs-cn-hangzhou.aliyuncs.com'
client = OpenApiClient(config)
params = open_api_models.Params(
style='RPC', # The API style.
version='2014-05-26', # The version number of the operation.
action='DescribeInstanceTypeFamilies', # The API operation.
method='POST', # The HTTP method of the API operation.
pathname='/', # The path of the API operation. The default path of RPC-style API operations is /.
protocol='HTTPS', # The protocol of the API operation.
auth_type='AK',
req_body_type='json', # The format of the request body.
body_type='json' # The format of the response body.
)
query = {'RegionId': 'cn-hangzhou'}
# Create an API request.
request = open_api_models.OpenApiRequest(
query=OpenApiUtilClient.query(query),
)
# Create a runtime configuration object.
runtime = util_models.RuntimeOptions()
# Call the operation and return the response.
response = client.call_api(params, request, runtime)
# The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
print(response)
@staticmethod
async def main_async():
"""
The asynchronous main function, which is used to show how to call an API operation of an Alibaba Cloud service in asynchronous mode.
"""
# 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']
)
# Specify the endpoint of the service.
config.endpoint = f'ecs-cn-hangzhou.aliyuncs.com'
client = OpenApiClient(config)
params = open_api_models.Params(
style='RPC', # The API style.
version='2014-05-26', # The version number of the operation.
action='DescribeInstanceTypeFamilies', # The API operation.
method='POST', # The HTTP method of the operation.
pathname='/', # The path of the API operation.
protocol='HTTPS', # The protocol of the operation.
auth_type='AK',
req_body_type='json', # The format of the request body.
body_type='json' # The format of the response body.
)
query = {'RegionId': 'cn-hangzhou'}
# Create an API request.
request = open_api_models.OpenApiRequest(
query=OpenApiUtilClient.query(query),
)
# Create a runtime configuration object.
runtime = util_models.RuntimeOptions()
# Call the operation in asynchronous mode.
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(
# The name of the operation.
action='DescribeClustersV1',
# The version number of the API operation.
version='2015-12-15',
# The protocol of the API operation.
protocol='HTTPS',
# The HTTP method of the API operation.
method='GET',
auth_type='AK',
style='ROA',
# The path of the operation. You can obtain the path of an ROA-style operation from the data.path parameter in the API metadata.
pathname=f'/api/v1/clusters',
# The format of the request body.
req_body_type='json',
# The format of the response body.
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 response is of the MAP type, which contains the response body, response headers, and 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(
# The name of the operation.
action='DescribeClustersV1',
# The version number of the API operation.
version='2015-12-15',
# The protocol of the API operation.
protocol='HTTPS',
# The HTTP method of the API operation.
method='GET',
auth_type='AK',
style='ROA',
# The URL of the API operation.
pathname=f'/api/v1/clusters',
# The format of the request body.
req_body_type='json',
# The format of the response body.
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 response is of the MAP type, which contains the response body, response headers, and HTTP status code.
await client.call_api_async(params, request, runtime)
if __name__ == '__main__':
Sample.main()