Todos os produtos
Search
Central de documentação

Alibaba Cloud SDK:Generic calls

Última atualização: Sep 15, 2026

O Alibaba Cloud SDK V1.0 for Python oferece suporte a chamadas de API genéricas. Esse recurso permite invocar qualquer operação de API instalando apenas a biblioteca principal, sem a necessidade de SDKs específicos para cada serviço.

Benefícios

  1. Leveza: invoque qualquer operação de API instalando apenas o aliyun-python-sdk-core. Não é necessário utilizar SDKs específicos de serviço.

  2. Iteração rápida: utilize as operações de API mais recentes imediatamente, mesmo quando o SDK específico do serviço estiver indisponível ou desatualizado.

Generic calls and specialized calls.

Observações de uso

Antes de fazer uma chamada genérica, obtenha os API metadata necessários, incluindo a versão da API, a URL da solicitação e o tipo de parâmetro.

Instale a biblioteca principal

Execute o comando a seguir para instalar a biblioteca principal:

pip install aliyun-python-sdk-core

Invoque uma operação de API

Inicialize um client de solicitação

Use o módulo client em aliyunsdkcore para criar um client que invoque API operations. Este exemplo usa um AccessKey pair. Outros tipos de credenciais estão disponíveis em Manage access credentials.

Nota

Para evitar vazamentos de AccessKey, armazene seu AccessKey pair em variáveis de ambiente. Configure environment variables in Linux, macOS, and Windows.

import os
from aliyunsdkcore.client import AcsClient

# Use an AccessKey pair to directly initialize the request client. 
client = AcsClient(
    os.environ['ALIYUN_ACCESS_KEY_ID'],
    os.environ['ALIYUN_ACCESS_KEY_SECRET'],
    region_id='cn-hangzhou',
    # verify=False  # Disable SSL certificate verification.
    # proxy={'http': 'http://127.0.0.1:9898'}, # Configure a proxy.
    # proxy={'https': 'http://<user>:<password>@127.0.0.1:8989'},
    connect_timeout=10, # Configure a timeout period for connection requests.
    timeout=15 # Configure a timeout period for read requests.
)

Configure os parâmetros da solicitação

Use CommonRequest para definir parâmetros comuns e específicos da API operation. Os detalhes dos parâmetros comuns estão em Advanced settings.

Nota

O módulo request converte os metadados da API (versão, URL e tipo de parâmetro) em uma solicitação HTTP válida e retorna a resposta bruta. A forma como os parâmetros são passados depende do estilo da API.

Parâmetros específicos da operação

Os metadados da API determinam como transmitir cada parâmetro. Por exemplo, a operação DescribeInstanceStatus define {"name":"RegionId","in":"query",...}}, em que "in":"query" indica que RegionId deve ser passado via putQueryParameter.

Descrição

Como o parâmetro é transmitido

"in":"query"

dd_query_param(self, k, v)

Nota

Formato para múltiplos pares chave-valor: dd_query_param("key.1","value1");

add_query_param("key.2","value2");...

"in":"body" ou "in": "formData"

add_body_params(self, k, v)

Nota

Converta valores de parâmetros não string em strings JSON.

Upload de arquivos

set_content(self, content)

Nota

Defina o parâmetro content como um array de bytes.

# 2. Create a CommonRequest object and configure the basic information about and request parameters of the API operation. 
request = CommonRequest()

# 2.1 Configure common request parameters.
request.set_domain('ecs-cn-hangzhou.aliyuncs.com')  # The endpoint of the API.
request.set_version('2014-05-26')  # The API version number.
request.set_action_name('DescribeInstanceStatus')  # The name of the API operation. When you call an RPC-style API operation, you must configure set_action_name() to specify the name of the API operation.
request.set_method('POST')  # The request method of the API operation.
request.set_protocol_type('HTTPS')  # The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS. 
# request.set_uri_pattern('/')  # The resource path, which is required by ROA-style API operations. Do not configure this parameter for RPC-style API operations. 

# 2.2 Configure operation-specific request parameters.
# Scenario 1: Specify the query parameters in add_query_param(self, k, v).
InstanceIds = [
    "i-bp1axhql4dqXXXXXXXX",
    "i-bp124uve8zqXXXXXXXX"
]
for depth1 in range(len(InstanceIds)):
    request.add_query_param('InstanceId.' + str(depth1 + 1), InstanceIds[depth1])
request.add_query_param('PageNumber', '1')
request.add_query_param('PageSize', '30')

# Scenario 2: Specify the body parameters in add_body_params(self, k, v).
# request.add_body_params('key1', 'value1')
# request.add_body_params('key2', 'value2')
# request.add_body_params('key3', 'value3')

# Scenario 3: Use set_content(self, content) to upload files, and set content to a byte array.
# file_path = "<FILE_PATH>" # Replace <FILE_PATH> with the actual file path.
# with open(file_path, 'rb') as file:
#    Read the image content as a byte array.
#    ByteArray = file.read()
# request.set_content(ByteArray)

Envie a solicitação

Invoque do_action_with_exception no client com a instância de CommonRequest.

# Initiate a request.
response = client.do_action_with_exception(request)
# If the response is of the byte type, the request ID and response parameters are returned.
print(f"response:\n{response}")
# Parse the response in JSON format.
response_json = json.loads(response.decode('utf-8'))  # Convert the response to a Python dictionary.
print("RequestId:", response_json["RequestId"])  # The request ID.

Exemplos

Exemplo: Invoque uma operação de API estilo RPC

Invoque a operação DescribeInstanceStatus do Elastic Compute Service (ECS) com uma chamada genérica estilo RPC.

import os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

class Sample:

    @staticmethod
    def main():
        # Use an AccessKey pair to directly initialize the request client. 
        client = AcsClient(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                           'cn-hangzhou')
        # Create a request object.
        request = CommonRequest()
        request.set_domain('ecs-cn-hangzhou.aliyuncs.com')  # The endpoint of the API.
        request.set_version('2014-05-26')  # The API version number.
        request.set_action_name('DescribeRegions')  # The name of the API operation. When you call an RPC-style API operation, you must configure set_action_name() to specify the name of the API operation.
        request.set_method('POST')  # The request method of the API operation.
        request.set_protocol_type('HTTPS')  # The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS. 
        InstanceIds = [
            "i-bp1axhql4dqXXXXXXXX",
            "i-bp124uve8zqXXXXXXXX"
        ]
        for depth1 in range(len(InstanceIds)):
            request.add_query_param('InstanceId.' + str(depth1 + 1), InstanceIds[depth1])
        request.add_query_param('PageNumber', '1')
        request.add_query_param('PageSize', '30')
        # Initiate a request and handle the response.
        response = client.do_action_with_exception(request)
        print(response)

if __name__ == '__main__':
    Sample.main()
     

Exemplo: Invoque uma operação de API estilo RESTful (ROA)

Invoque a operação DescribeClustersV1 do Container Service for Kubernetes (ACK) com uma chamada genérica estilo RESTful (ROA).

import os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

class Sample:

    @staticmethod
    def main():
        # Use an AccessKey pair to directly initialize the request client. 
        client = AcsClient(
            os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
            'cn-hangzhou')
        # Create a request object.
        request = CommonRequest()
        request.set_domain('cs.aliyuncs.com')  # The endpoint of the API operation.
        request.set_version('2015-12-15')  # The API version number.
        request.set_uri_pattern(
            f'/api/v1/clusters')  # The URL of the API operation. When you call an ROA-style API operation, you must configure set_uri_pattern() to specify a complete URL of the API operation. You can obtain the URL of an API operation from the API metadata. 
        request.set_method('GET')  # The request method of the API operation.
        request.add_query_param('name', 'cluster-demo')  # Configure the request parameters.
        # Initiate a request and handle the response.
        response = client.do_action_with_exception(request)
        print(response)

if __name__ == '__main__':
    Sample.main()

FAQ

  1. O que fazer se a mensagem de erro "Error:MissingParameter The input parameter "AccessKeyId" that is mandatory for processing this request is not supplied" for retornada?

    Causa: O AccessKey pair não está configurado corretamente.

    Soluções:

    1. Verifique se as variáveis de ambiente ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET estão definidas.

      Linux/macOS

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

      Windows

      echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
      echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

      Se um AccessKey pair válido for retornado, as variáveis de ambiente estarão configuradas corretamente. Caso contrário, reconfigure as variáveis de ambiente. Configure environment variables in Linux, macOS, and Windows.

    2. Verifique se há erros relacionados ao AccessKey pair no código.

      Exemplo de solicitação com erro:

      AccessKeyId = os.environ['yourAccessKeyID'],
      AccessKeySecret = os.environ['yourAccessKeySecret']
      Nota

      O erro ocorre porque as strings passadas para os.environ são nomes literais de chaves, e não as credenciais. Defina ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET como variáveis de ambiente para que os.environ leia os valores corretos.

      Exemplo de solicitação bem-sucedida:

      os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], 
      os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  2. O que fazer se a mensagem de erro "aliyunsdkcore.acs_exception.exceptions.ServerException: HTTP Status: 400 Error:MissingParameter The input parameter "Timestamp" that is mandatory for processing this request is not supplied" for retornada?

    Causa: uri_pattern foi definido para uma operação estilo RPC.

    Solução: Remova uri_pattern dos parâmetros da solicitação.