To integrate Alibaba Cloud SDK V2.0, you must perform the following steps: configure an access credential, import the SDK to your project, and write code for calling API operations. This topic describes how to integrate Alibaba Cloud SDK V2.0. In this example, Alibaba Cloud SDK V2.0 for Python
is used to call the SendSms operation of Short Message Service (SMS) to send a text message.
Prerequisites
Python 3.7 or later is installed.
1. Install the SDK for Python
Install the SDK for specialized calls
Alibaba Cloud SDK V2.0 incorporates the main API logic, such as parameter processing, request assembly, and response processing. You can make API requests by installing the SDK of an Alibaba Cloud service as a dependency.
Log on to SDK Center and select the service whose SDK you want to use. In this example, Short Message Service (SMS) is selected.
On the Short Message Service page, select Python in the All languages section. On the Quick Start tab, obtain the installation method of Short Message Service (SMS) SDK.
Install the SDK for generic calls
You do not need to install the SDK of a service to make generic calls. You need to only import the alibabacloud-tea-openapi
core package. For information about the latest version of the core package, see alibabacloud-tea-openapi. Run the following command to install the core package:
pip install alibabacloud-tea-openapi
2. Configure an access credential
You must configure an access credential before you use Alibaba Cloud SDK V2.0 to call API operations. The following types of credentials are commonly used on Alibaba Cloud: AccessKey pairs
and Security Token Service (STS) tokens
. For more information, see Credential. To prevent leaks of credentials, you can configure the information about credentials in environment variables. For more information about other security solutions, see Credential security solutions. In this example, the ALIBABA_CLOUD_ACCESS_KEY_ID
and ALIBABA_CLOUD_ACCESS_KEY_SECRET
environment variables are configured.
Linux and macOS
Configure environment variables by using the export command
The temporary environment variables configured by using the export command are valid only for the current session. After you exit the session, the configured environment variables become invalid. To configure permanent environment variables, you can add the export command to the startup configuration file of the corresponding operating system.
Configure the AccessKey ID and press Enter.
# Replace <ACCESS_KEY_ID> with your AccessKey ID. export ALIBABA_CLOUD_ACCESS_KEY_ID=<ACCESS_KEY_ID>
Configure the AccessKey secret and press Enter.
# Replace <ACCESS_KEY_SECRET> with your AccessKey secret. export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET>
Check whether the configuration is successful.
Run the
echo $ALIBABA_CLOUD_ACCESS_KEY_ID
command. If the valid AccessKey ID is returned, the environment variables are configured.
Windows
Use GUI
Procedure
If you want to use GUI to configure environment variables in Windows 10, perform the following steps:
On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section. Then, configure the variables described in the following table.
Variable
Example
AccessKey ID
Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID
Variable value: LTAI4GDty8ab9W4Y1D****
AccessKey Secret
Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET
Variable value: IrVTNZNy5yQelTETg0cZML3TQn****
Check whether the configuration is successful.
On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the
echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
andecho %ALIBABA_CLOUD_ACCESS_KEY_SECRET%
commands. If the valid AccessKey pair is returned, the configuration is successful.
Use CMD
Procedure
Open a Command Prompt window as an administrator and run the following commands to add environment variables in the operating system:
setx ALIBABA_CLOUD_ACCESS_KEY_ID LTAI4GDty8ab9W4Y1D**** /M setx ALIBABA_CLOUD_ACCESS_KEY_SECRET IrVTNZNy5yQelTETg0cZML3TQn**** /M
/M
indicates that the environment variable is of system level. You can choose not to use this parameter when you configure a user-level environment variable.Check whether the configuration is successful.
On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the
echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
andecho %ALIBABA_CLOUD_ACCESS_KEY_SECRET%
commands. If the valid AccessKey pair is returned, the configuration is successful.
Use Windows PowerShell
In PowerShell, configure new environment variables. The environment variables apply to all new sessions.
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::User)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::User)
Configure environment variables for all users. You must run the following commands as an administrator.
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::Machine)
Configure temporary environment variables. The environment variables apply only to the current session.
$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "LTAI4GDty8ab9W4Y1D****"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "IrVTNZNy5yQelTETg0cZML3TQn****"
In PowerShell, run the Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_ID
and Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_SECRET
commands. If the valid AccessKey pair is returned, the configuration is successful.
3. Call an API operation
In this example, the sample code of a specialized call is used. For more information about how to make a generic call, see Generic calls.
3.1 Initialize a request client
You can use multiple methods to initialize a request client. In this example, an AccessKey pair is used to initialize a request client. For more information, see Manage access credentials.
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
import os
@staticmethod
def create_client() -> Dysmsapi20170525Client:
# If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your Alibaba Cloud account may be compromised. The following lines are provided for reference only.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. ,
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. ,
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
config.endpoint = f'dysmsapi.aliyuncs.com'
return Dysmsapi20170525Client(config)
3.2 Create a request object and configure runtime configurations
In most cases, you can create a request object and specify the parameters based on your business requirements. You can also customize runtime configurations.
# Create a request object and specify the parameters.
send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
# The mobile numbers to which you want to send a text message.
phone_numbers='<YOUR_VALUE>',
# The name of the SMS signature.
sign_name='<YOUR_VALUE>',
# The code of the SMS template.
template_code='<YOUR_VALUE>',
# The variables of the SMS template. Specify the value in the JSON format. Example: {"code":"1234","name":"1234","time":"1234"}.
template_param='{"code":"1234","name":"1234","time":"1234"}'
)
# Create a runtime configuration object.
runtime = util_models.RuntimeOptions()
3.3 Initiate an API request
In Alibaba Cloud SDK V2.0, the client of each Alibaba Cloud service contains all the API operations provided by the service. In addition, Alibaba Cloud SDK V2.0 provides three methods to define each API operation. This design aims to improve the flexibility and efficiency of development, and ensure that you can call API operations in an optimal way based on your project requirements.
The name of the API operation is in lowercase letters.
<API operation name>
: uses the default runtime configurations to initiate a request. You do not need to specify runtime parameters.import os import sys from typing import List from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_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() -> Dysmsapi20170525Client: # If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your Alibaba Cloud account may be compromised. The following lines are provided for reference only. config = open_api_models.Config( # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. , access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. , access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] ) config.endpoint = f'dysmsapi.aliyuncs.com' return Dysmsapi20170525Client(config) @staticmethod def main( args: List[str], ) -> None: client = Sample.create_client() send_sms_request = dysmsapi_20170525_models.SendSmsRequest( # The mobile numbers to which you want to send a text message. phone_numbers='<YOUR_VALUE>', # The name of the SMS signature. sign_name='<YOUR_VALUE>', # The code of the SMS template. template_code='<YOUR_VALUE>', # The variables of the SMS template. Specify the value in the JSON format. Example: {"code":"1234","name":"1234","time":"1234"}. template_param='{"code":"1234","name":"1234","time":"1234"}' ) try: # If you copy and run the sample code, write your own code to display the response of the API operation. client.send_sms(send_sms_request) except Exception as error: # Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error message displayed in this example is for reference only. # The error message. print(error.message) # The URL of the corresponding error diagnostics page. print(error.data.get("Recommend")) UtilClient.assert_as_string(error.message) if __name__ == '__main__': Sample.main(sys.argv[1:])
<API operation name>_with_options
: uses the custom runtime configurations to initiate a request. For more information, see Advanced configuration.import os import sys from typing import List from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_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() -> Dysmsapi20170525Client: # If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your Alibaba Cloud account may be compromised. The following lines are provided for reference only. config = open_api_models.Config( # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. , access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. , access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] ) config.endpoint = f'dysmsapi.aliyuncs.com' return Dysmsapi20170525Client(config) @staticmethod def main( args: List[str], ) -> None: client = Sample.create_client() send_sms_request = dysmsapi_20170525_models.SendSmsRequest( # The mobile numbers to which you want to send a text message. phone_numbers='<YOUR_VALUE>', # The name of the SMS signature. sign_name='<YOUR_VALUE>', # The code of the SMS template. template_code='<YOUR_VALUE>', # The variables of the SMS template. Specify the value in the JSON format. Example: {"code":"1234","name":"1234","time":"1234"}. template_param='{"code":"1234","name":"1234","time":"1234"}' ) runtime = util_models.RuntimeOptions() try: # If you copy and run the sample code, write your own code to display the response of the API operation. client.send_sms_with_options(send_sms_request,runtime) except Exception as error: # Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error message displayed in this example is for reference only. # The error message. print(error.message) # The URL of the corresponding error diagnostics page. print(error.data.get("Recommend")) UtilClient.assert_as_string(error.message) if __name__ == '__main__': Sample.main(sys.argv[1:])
<API operation name>Advance
: used for API operations that require file uploading. By default, you must specify runtime parameters. The following sample code provides an example on how to initiate a request to upload a file and call an API operation to usethe human face and body recognition feature of Visual Intelligence API (VIAPI)
.# The dependency for the human face and body recognition feature of VIAPI. pip install alibabacloud_facebody20191230==5.1.2
import os import sys from typing import List from alibabacloud_facebody20191230.client import Client as facebody20191230Client from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_facebody20191230 import models as facebody_20191230_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() -> facebody20191230Client: # If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your Alibaba Cloud account may be compromised. The following lines are provided for reference only. config = open_api_models.Config( # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. , access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. , access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] ) config.endpoint = f'facebody.cn-shanghai.aliyuncs.com' return facebody20191230Client(config) @staticmethod def main( args: List[str], ) -> None: client = Sample.create_client() // Create a request object. detect_body_count_advance_request = facebody_20191230_models.DetectBodyCountAdvanceRequest() detect_body_count_advance_request.image_urlobject = open('<filepath>', 'rb') # Construct the runtime configuration object. runtimeOptions = util_models.RuntimeOptions() try: # If you copy and run the sample code, write your own code to display the response of the API operation. response = client.detect_body_count_advance(detect_body_count_advance_request, runtimeOptions) print(response) except Exception as error: # Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error message displayed in this example is for reference only. # The error message. print(error.message) # The URL of the corresponding error diagnostics page. print(error.data.get("Recommend")) UtilClient.assert_as_string(error.message) if __name__ == '__main__': Sample.main(sys.argv[1:])