Alibaba Cloud SDK for Java V2.0 admite llamadas genéricas a la API, las cuales permiten invocar cualquier operación de OpenAPI sin necesidad de instalar los SDK específicos de cada servicio.
Características
Ligero: solo se requiere la biblioteca principal de Alibaba Cloud SDK. No es necesario instalar el SDK de cada servicio.
Fácil de usar: cree parámetros de solicitud comunes y utilice un cliente común para iniciar las solicitudes. Las respuestas se devuelven en formatos comunes.
Para obtener más información, consulte Generic calls and specialized calls.
Notas de uso
Antes de hacer una llamada genérica, consulte los metadata of the API operation para obtener el estilo de la API, los parámetros de solicitud y la URL.
Instalar la biblioteca principal de Alibaba Cloud SDK
Ejecute el siguiente comando para instalar la biblioteca principal de Alibaba Cloud SDK V2.0 para PHP:
composer require alibabacloud/darabonba-openapi
Llamar a una operación de API
Inicializar un cliente de solicitud
Cree un objeto OpenApiClient para inicializar un cliente de solicitud y llamar a la operación de API. También puede usar la herramienta Credentials para inicializar el cliente. Para obtener más información, consulte Manage access credentials.
// getenv indicates that the AccessKey pair is obtained from environment variables. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
$config = new Config([
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
]);
// Specify the endpoint of the service. In this example, the endpoint of Elastic Compute Service (ECS) in the China (Hangzhou) region is used.
$config->endpoint = "ecs-cn-hangzhou.aliyuncs.com";
// $config->protocol = "HTTPS"; // Specify HTTPS as the protocol.
$client = new OpenApiClient($config);
// Use the default credential to initialize the credential client.
// $credentialClient = new Credential();
// $Config = new Config([
// Configure the credential.
// 'credential' => $credentialClient,
// // The domain name of the service.
// 'endpoint' => 'ecs-cn-hangzhou.aliyuncs.com'
// ]);
// $client = new OpenApiClient($Config);
Configurar la información de la operación de API
Use Params para configurar la operación de API, incluido el estilo de la API, la versión y el método de solicitud.
$params = new Params([
"action" => "DescribeInstanceTypeFamilies", // The API operation.
"version" => "2014-05-26", // The version number of the operation.
"protocol" => "HTTPS", // The protocol of the operation.
"method" => "POST", // The HTTP method of the operation.
"authType" => "AK", // The authentication method.
"pathname" => "/", // The URL of the operation.
"reqBodyType" => "json", // The format of the request body.
"bodyType" => "json",// The request body of the JSON type.
"style" => "RPC" // The API style, such as remote procedure call (RPC) and resource-oriented architecture (ROA).
]);
Configurar los parámetros de solicitud
Use OpenApiRequest para configurar los parámetros de solicitud. Según los metadatos de la operación de API, puede pasar los parámetros en una cadena de consulta, un cuerpo o un stream. Por ejemplo, el parámetro RegionId de la operación DescribeInstanceTypeFamilies se define como {"name":"RegionId","in":"query",...}} en los metadatos. "in":"query" indica que el parámetro RegionId se pasa en una cadena de consulta.
|
Forma de pasar el parámetro |
Descripción |
|
query |
Si los metadatos definen |
|
body |
Si los metadatos definen |
|
stream |
Para cargar archivos, pase streams de archivos mediante la configuración del parámetro Stream. |
// Scenario 1: Configure a query string.
$query = ["RegionId" => "cn-hangzhou"];
$request = new OpenApiRequest([
"query" => OpenApiUtilClient::query($query),
]);
// Scenario 2: Configure the body and set reqBodyType to json.
// $body = [
// "param1" => "value1"
// ];
// $request = new OpenApiRequest([
// "body" => OpenApiUtilClient::query($body)
// ]);
// Scenario 3: Configure the Stream parameter to pass file streams
// $request = new OpenApiRequest([
// "stream" => "<FILE_STREAM>", // The file stream that you want to pass.
// ]);
// Scenario 4: Configure a request body and set reqBodyType to formData.
// $formData = [
// "param1" => "value1",
// ];
// $request = new OpenApiRequest([
// "body" => $formData,
// ]);
Iniciar una solicitud
Use OpenApiClient para llamar al método callApi e iniciar una solicitud. Puede especificar parámetros de tiempo de ejecución, como los valores de tiempo de espera y la configuración del proxy. Para obtener más información, consulte Advanced settings.
// Create a RuntimeOptions instance. You can configure runtime parameters in the RuntimeOptions instance, such as the timeout period.
$runtime = new RuntimeOptions([]);
// $runtime -> ignoreSSL = true; // A value of true specifies to disable certificate verification. A value of false specifies to enable certificate verification.
// $runtime -> httpProxy = "http://127.0.0.1:8080"; // The proxy settings.
// $runtime -> httpsProxy = "https://username:password@proxyServer:port";
// $runtime -> noProxy = "127.0.0.1,localhost";
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
$response = $client->callApi($params, $request, $runtime);
var_dump($response);
Código de ejemplo
Llamar a una operación de API RPC
En el siguiente ejemplo se hace una llamada genérica a la operación DescribeInstanceTypeFamilies de ECS.
<?php
namespace AlibabaCloud\SDK\Sample;
require_once 'vendor/autoload.php';
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\OpenApiUtil\OpenApiUtilClient;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use Darabonba\OpenApi\Models\OpenApiRequest;
use Darabonba\OpenApi\Models\Params;
use Darabonba\OpenApi\OpenApiClient;
class Sample
{
public static function main()
{
// Obtain the AccessKey pair from environment variables. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
$config = new Config([
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
]);
// Specify the endpoint of the service. In this example, the endpoint of Elastic Compute Service (ECS) in the China (Hangzhou) region is used.
$config->endpoint = "ecs-cn-hangzhou.aliyuncs.com";
$client = new OpenApiClient($config);
$params = new Params([
"action" => "DescribeInstanceTypeFamilies", // The API operation.
"version" => "2014-05-26", // The version number of the operation.
"protocol" => "HTTPS", // The protocol of the operation.
"method" => "POST", // The HTTP method of the operation.
"authType" => "AK", // The authentication method.
"style" => "RPC", // The API style.
"pathname" => "/", // The URL of the operation.
"reqBodyType" => "json", // The format of the request body.
"bodyType" => "json",// The request body of the JSON type.
]);
// Configure the query parameters.
$query = ["RegionId" => "cn-hangzhou"];
$request = new OpenApiRequest([
"query" => OpenApiUtilClient::query($query),
]);
// Create a RuntimeOptions instance. You can configure runtime parameters in the RuntimeOptions instance, such as the timeout period.
$runtime = new RuntimeOptions([]);
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
$response = $client->callApi($params, $request, $runtime);
var_dump($response);
}
}
Sample::main();
Llamar a una operación de API RESTful
En el siguiente ejemplo se hace una llamada genérica a la operación DescribeClustersV1 de ACK.
<?php
namespace AlibabaCloud\SDK\Sample;
require_once 'vendor/autoload.php';
use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\OpenApiUtil\OpenApiUtilClient;
use Darabonba\OpenApi\Models\Config;
use Darabonba\OpenApi\Models\Params;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\OpenApiRequest;
class Sample
{
public static function main()
{
$config = new Config([
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
]);
$config->endpoint = "cs.cn-qingdao.aliyuncs.com";
$client = new OpenApiClient($config);
$params = new Params([
// The name of the API 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",
"authType" => "AK",
"style" => "ROA",
// The path of the API operation.
"pathname" => "/api/v1/clusters",
// The format of the request body.
"reqBodyType" => "json",
// The format of the response body.
"bodyType" => "json"
]);
// query params
$queries = [
"name" => "cluster-demo"
];
$request = new OpenApiRequest([
"query" => OpenApiUtilClient::query($queries)
]);
// runtime options
$runtime = new RuntimeOptions([]);
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
$response = $client->callApi($params, $request, $runtime);
var_dump($response);
}
}
Sample::main();