Todos os produtos
Search
Central de documentação

Alibaba Cloud SDK:Chamadas genéricas

Última atualização: Jun 28, 2026

O Alibaba Cloud SDK for Java V2.0 oferece suporte a chamadas de API genéricas, que permitem invocar qualquer operação OpenAPI sem instalar SDKs específicos para cada serviço.

Características

Leveza: requer apenas a biblioteca principal do Alibaba Cloud SDK. Não é necessário instalar o SDK de cada serviço individualmente.

Facilidade de uso: crie parâmetros de solicitação comuns e use um cliente genérico para iniciar as requisições. As respostas retornam em formatos padronizados.

Para mais informações, consulte Chamadas genéricas e chamadas especializadas.

Observações de uso

Antes de fazer uma chamada genérica, visualize os metadados da operação de API para obter o estilo da API, os parâmetros de solicitação e a URL.

Instale a biblioteca principal do Alibaba Cloud SDK

Execute o comando abaixo para instalar a biblioteca principal do Alibaba Cloud SDK V2.0 for PHP:

composer require alibabacloud/darabonba-openapi

Invoque uma operação de API

Inicialize um cliente de solicitação

Crie um objeto OpenApiClient para inicializar um cliente de solicitação e invocar a operação de API. Também é possível usar a ferramenta Credentials para inicializar o cliente. Para mais detalhes, consulte Gerenciar credenciais de acesso.

        // 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);

Configure as informações da operação de API

Use Params para configurar a operação de API, incluindo o estilo da API, a versão e o método de solicitação.

         $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).
        ]);

Configure os parâmetros de solicitação

Use OpenApiRequest para definir os parâmetros da requisição. É possível passar parâmetros via query string, corpo da requisição ou stream, conforme os metadados da operação de API. Por exemplo, o parâmetro RegionId da operação DescribeInstanceTypeFamilies está definido como {"name":"RegionId","in":"query",...}} nos metadados. A definição "in":"query" indica que o parâmetro RegionId deve ser enviado na query string.

Forma de envio do parâmetro

Descrição

query

Se os metadados definirem "in":"query", envie o parâmetro na query string.

body

Se os metadados especificarem "in":"body'' ou "in": "formData", transmita o parâmetro no corpo da requisição. Ao enviar parâmetros dessa forma, defina um valor para o parâmetro reqBodyType de acordo com o tipo de corpo utilizado.

stream

Para fazer upload de arquivos, passe fluxos de arquivo configurando o 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,  
        // ]);

Inicie uma solicitação

Use OpenApiClient para chamar o método callApi e iniciar a requisição. Especifique parâmetros de tempo de execução, como timeout e configurações de proxy. Para mais informações, consulte Configurações avançadas.

        // 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 exemplo

Invoque uma operação de API RPC

O exemplo a seguir faz uma chamada genérica para a operação DescribeInstanceTypeFamilies do 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();

Invoque uma operação de API RESTful

Este exemplo demonstra uma chamada genérica para a operação DescribeClustersV1 do 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();