Install the Python SDK
This topic uses an example that calls the GetProject API of Function AI to demonstrate how to install and use the Python SDK. For the GetProject API reference, see GetProject - Query a project.
Prerequisites
Calling an Alibaba Cloud OpenAPI operation requires an AccessKey pair. The AccessKey pair of an Alibaba Cloud account has full permissions on all resources. If this AccessKey pair is leaked, it poses a high security threat. We recommend that you use the AccessKey pair of a Resource Access Management (RAM) user with only the minimum required permissions.
The AccessKey pair is configured as an environment variable.
For more information, see Configure environment variables on Linux, macOS, and Windows.
Environment requirements
Python 3.7 or later
The
pippackage management tool is installed.
Install the SDK
Run the following command to install the Function AI SDK:
pip install alibabacloud_devs20230714Use the SDK
1. Initialize the client
In the SDK, you must use a client to make all OpenAPI calls. Before you call an OpenAPI operation, you must initialize the client. The client can be initialized in several ways. This example shows how to initialize the client using an AccessKey pair. For more information about other initialization methods, see Manage access credentials.
# -*- coding: utf-8 -*-
import os
import sys
from typing import List
from alibabacloud_devs20230714.client import Client as Devs20230714Client
from alibabacloud_tea_openapi import models as open_api_models
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> Devs20230714Client:
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint='devs.cn-hangzhou.aliyuncs.com'
)
return Devs20230714Client(config)2. Build the request object for the operation
When you call an OpenAPI operation, you must use the request object provided by the SDK to pass parameters. Before you build the request object, see the GetProject - Query a project API reference to obtain information about the parameters.
The naming convention for request objects is `{APIName}Request`. For example, the request object for the GetProject operation is `GetProjectRequest`.
// Construct the request object.
request = Devs20230714Client.models.GetProjectRequest()
request.project_name = 'my-project'3. Initiate the call
When you call an OpenAPI operation using the client, you can set runtime parameters, such as timeout and proxy configurations. For more information, see Advanced configurations.
The naming convention for response objects is `{APIName}Response`. For example, the response object for the GetProject operation is `GetProjectResponse`.
// Set runtime parameters.
runtime = RuntimeOptions()
// Call the GetProject operation.
response = client.get_project_with_options(request, runtime)4. Handle exceptions
The Python SDK categorizes exceptions into `UnretryableException` and `TeaException`.
`UnretryableException`: This exception is typically caused by network issues and is thrown after the maximum number of retries for a network request is reached.
`TeaException`: This exception is typically related to business errors.
Take appropriate measures to handle exceptions, such as propagating exceptions, recording logs, and attempting to recover. This helps ensure the robustness and stability of your system.
5. Complete example
# -*- coding: utf-8 -*-
import os
import sys
from typing import List
from alibabacloud_devs20230714.client import Client as Devs20230714Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> Devs20230714Client:
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint='devs.cn-hangzhou.aliyuncs.com'
)
return Devs20230714Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = Sample.create_client()
runtime = util_models.RuntimeOptions()
headers = {}
try:
# If you copy this code to run, print the return value of the API operation.
client.get_project_with_options('my-project', headers, runtime)
except Exception as error:
# The following code is for demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
# Error message
print(error.message)
# Diagnosis address
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
@staticmethod
async def main_async(
args: List[str],
) -> None:
client = Sample.create_client()
runtime = util_models.RuntimeOptions()
headers = {}
try:
# If you copy this code to run, print the return value of the API operation.
await client.get_project_with_options_async('my-project', headers, runtime)
except Exception as error:
# The following code is for demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
# Error message
print(error.message)
# Diagnosis address
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
if __name__ == '__main__':
Sample.main(sys.argv[1:])More information
In addition to the method described in this topic, you can use generalized calls to call Function AI OpenAPI operations. For more information, see Generalized calls.