Alibaba Cloud SDK V1.0 for PHP supports generic API calls. This topic describes how to make generic calls by using Alibaba Cloud SDK V1.0 for PHP.
Characteristics
Lightweight: You can use Alibaba Cloud SDK V1.0 for PHP to call all API operations by installing only the core library of Alibaba Cloud SDK, without the need to install the SDK of each service.
Fast iteration and compatibility: If a cloud service does not provide an SDK, or the SDK is not updated for the latest API operations, you can make generic calls. This way, you can call the latest API operations without the need to wait for SDK updates.
For more information, see Generic calls and specialized calls.
Usage notes
Before you make a generic call, manually obtain and specify the required metadata, including the API version, request URL, and parameter type. For more information, see API metadata.
Install the core library of Alibaba Cloud SDK V1.0 for PHP
Run the following command on your terminal to install the core library of Alibaba Cloud SDK V1.0 for PHP:
composer require alibabacloud/clientCall an API operation
Initialize a request client
In the AlibabaCloud package, create a client to initialize the request client, and use the client to call API operations. In this example, an AccessKey pair is used to initialize the request client. For more information, see Manage access credentials.
To prevent AccessKey leaks, you can record the AccessKey pair in environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.
use AlibabaCloud\Client\AlibabaCloud;
// getenv indicates that the AccessKey pair obtained from environment variables is used to initialize the client.
AlibabaCloud::accessKeyClient(
getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
)
->regionId('cn-hangzhou') // Specify the region ID.
->asDefaultClient(); // Specify the client as the default client.
Configure the API operation information and request parameters
Use the client in the AlibabaCloud package to configure the basic information about and request parameters of the API operation. For more information about the common request parameters, see Advanced settings.
The request module is used to convert the API metadata, such as the version number, URL, and parameter type, to a valid HTTP request through a standard request configuration process, and then return the original response data. How parameters are passed are determined by the API style and design.
Operation-specific parameters
How a request parameter is passed is determined by the metadata of the API operation. For example, the DescribeInstanceStatus API operation is defined as {"name":"RegionId","in":"query",...}} in the metadata. In this case, "in":"query" indicates that the region ID (RegionId) must be passed in options([ 'query' => [ 'key1' => 'value1'] ]).
Scenario | How the parameter is passed |
| options([ 'query' => [ 'key1' => 'value1'] ]) Note To specify a collection of key-values pairs, specify them in the following format: 'query' => [ 'key.1' => 'value1','key.2' => 'value2']... |
| options([ 'form_params' => [ 'key1' => 'value1'] ]) Note If the request parameter does not specify a string, convert the parameter value to a JSON string and specify the string as the parameter value. |
// The query parameters when they are of the collection type.
$instanceIDs = ["i-bp1axhql4dqXXXXXXXX", "i-bp124uve8zqXXXXXXXX"];
// Common parameters.
$queryParams = [
'RegionId' => 'cn-hangzhou',
'PageNumber' => 1,
'PageSize' => 30,
];
// Process the collection parameters by converting them to the format of InstanceId.1, InstanceId.2.
foreach ($instanceIDs as $index => $id) {
$queryKey = 'InstanceId.' . ($index + 1);
$queryParams[$queryKey] = $id;
}
// Configure the basic information about and request parameters of the API operation.
$result = AlibabaCloud::rpc() // The API operation style, such as remote procedure call (RPC) and resource-oriented architecture (ROA).
// 1.Configure the basic information about the API operation.
->host('ecs.cn-hangzhou.aliyuncs.com')
->product('Ecs') // The service name.
->version('2014-05-26') // Make sure that the version number must be the same as that in the API reference.
->action('DescribeInstanceStatus') // The name of the API operation. When you call an RPC-style API operation, you must configure action() to specify the name of the API operation.
->method('POST') // The request method. Valid values: GET and POST.
->setProtocolType('HTTPS') // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
// ->pathPattern() // The resource path, which is required by ROA-style API operations. Do not configure this parameter for RPC-style API operations.
// 2.Configure the request parameters.
->options([
// Scenario 1: Configure query parameters.
'query' => $queryParams
// Scenario 2: Configure the request body in form_params.
// 'form_params' => [
// 'key1' => 'value1',
// 'key2' => 'value2',
// 'key3' => 'value3',
// ],
])
Initiate a request
Use the client to initiate a request by calling the request() function.
// Call an RPC-style API operation.
$result = AlibabaCloud::rpc()
->request()
// Call an ROA-style API operation.
// $result = AlibabaCloud::roa()
// ->request()
// If the response is of the byte type, the request ID and response parameters are returned.
print_r($result->toArray()); 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.
<?php
namespace AlibabaCloud\SDK\Sample;
require_once 'vendor/autoload.php';
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class Sample
{
public static function main()
{
// getenv indicates that the AccessKey pair obtained from environment variables is used to initialize the client.
AlibabaCloud::accessKeyClient(
getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
)
->regionId('cn-hangzhou') // Specify the region ID.
->asDefaultClient(); // Specify the client as the default client.
// Configure query parameters when they are of the collection type.
$instanceIDs = ["i-bp1axhql4dqXXXXXXXX", "i-bp124uve8zqXXXXXXXX"];
// Common parameters.
$queryParams = [
'RegionId' => 'cn-hangzhou',
'PageNumber' => 1,
'PageSize' => 30,
];
// Process the collection parameters by converting them to the format of InstanceId.1, InstanceId.2.
foreach ($instanceIDs as $index => $id) {
$queryKey = 'InstanceId.' . ($index + 1);
$queryParams[$queryKey] = $id;
}
try {
$result = AlibabaCloud::rpc()
->method('POST') // The request method.
->verify(false) // Disable certification authentication.
->debug(true) // Enable logging.
->setProtocolType('HTTPS') // Configure a protocol.
->host('ecs.cn-hangzhou.aliyuncs.com') // Configure the endpoint.
->version('2014-05-26') // Make sure that the version number must be the same as that in the API reference.
->action('DescribeInstanceStatus') // Specify the API operation name.
// Configure request parameters.
->options([
'query' => $queryParams
])
// Send the request.
->request();
print_r($result->toArray());
} catch (ClientException | ServerException $e) {
echo $e->getErrorMessage();
} catch (ServerException $exception) {
print_r($exception->getErrorMessage());
}
}
}
Sample::main();Example: Call a RESTful-style (ROA-style) API operation
The following code shows how to use CommonRequest to call the DescribeClustersV1 operation of Container Service for Kubernetes (ACK):
<?php
namespace AlibabaCloud\SDK\Sample;
require_once 'vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class Sample
{
public static function main()
{
try {
$result = AlibabaCloud::roa()
->regionId('cn-hangzhou) // The region ID. If this parameter is not specified, the region of the client or the default region is used.
->product('CS') // The service name.
->version('2015-12-15 ') // The service version.
->serviceCode('cs') // The service code for addressing. This parameter is optional.
->endpointType('openAPI') // The endpoint type. This parameter is optional.
->method('GET') // The request method.
->host('cs.aliyun.com ') // The domain name. If this parameter is specified, addressing is not performed. If a service uses bearer tokens for authentication, you must specify the domain name.
->pathPattern('/api/v1/clusters') // The URL of the API operation. When you call an ROA-style API operation, you must configure pathPattern() to specify the complete URL of the API operation. You can obtain the URL of an API operation from the API metadata.
->request(); // Initiate the request and obtain the result. This parameter must be at the end of the settings.
print_r($result->toArray());
} catch (ClientException $exception) {
print_r($exception->getErrorMessage());
} catch (ServerException $exception) {
print_r($exception->getErrorMessage());
}
}
}
Sample::main();FAQ
What can I do if the "Fatal error: Uncaught AlibabaCloud\Client\Exception\ClientException: AccessKey ID cannot be empty in XXX" error message is returned?
Cause: The AccessKey pair is not correctly configured.
Solutions:
Run the following commands to check whether the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
Linux/macOS
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRETWindows
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%If a valid AccessKey pair is returned, the environment variables are properly configured. If no AccessKey pair or an invalid AccessKey pair is returned, configure the environment variables as required. For more information, see Configure environment variables in Linux, macOS, and Windows.
Check for errors related to the AccessKey pair in the code.
Sample error request:
AlibabaCloud::accessKeyClient( getenv('yourAccessKeyID'), getenv('yourAccessKeySecret') )NoteIn the preceding sample error request, the input values of getenv() are used as the AccessKey pair. However, this function is used to read values from the environment variables. After you specify the environment variable names as ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET on your machine, getenv can read the values from the environment variables.
Sample success request:
AlibabaCloud::accessKeyClient( getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET') )