Todos los productos
Search
Centro de documentos

Alibaba Cloud SDK:Generic calls

Última actualización: Sep 05, 2026

Alibaba Cloud SDK V1.0 for Python admite llamadas genéricas a la API. Estas le permiten invocar cualquier operación de la API con solo instalar la biblioteca principal, sin necesidad de usar los SDK específicos de cada servicio.

Ventajas

  1. Ligereza: invoque cualquier operación de la API con solo instalar aliyun-python-sdk-core. No se requieren SDK específicos por servicio.

  2. Iteración rápida: llame a las operaciones de la API más recientes de inmediato, incluso cuando el SDK específico del servicio no esté disponible o se encuentre desactualizado.

Generic calls and specialized calls.

Notas de uso

Antes de hacer una llamada genérica, obtenga la API metadata obligatoria, como la versión de la API, la URL de la solicitud y el tipo de parámetro.

Instalar la biblioteca principal

Ejecute el siguiente comando para instalar la biblioteca principal:

pip install aliyun-python-sdk-core

Invocar una operación de la API

Inicializar un cliente de solicitudes

Utilice el módulo client de aliyunsdkcore para crear un client que invoque las API operations. Este ejemplo utiliza un AccessKey pair. En Manage access credentials encontrará otros tipos de credenciales disponibles.

Nota

Para evitar filtraciones, almacene su AccessKey pair en variables de entorno. 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.
)

Configurar los parámetros de la solicitud

Use CommonRequest para establecer los parámetros comunes y los específicos de la API operation. Los detalles de los parámetros comunes se encuentran en Advanced settings.

Nota

El módulo request convierte los metadatos de la API (versión, URL y tipo de parámetro) en una solicitud HTTP válida y devuelve la respuesta sin procesar. La forma de pasar los parámetros depende del estilo de la API.

Parámetros específicos de la operación

Los metadatos de la API determinan cómo se pasa cada parámetro. Por ejemplo, la operación DescribeInstanceStatus define {"name":"RegionId","in":"query",...}}, donde "in":"query" indica que RegionId debe pasarse mediante putQueryParameter.

Descripción

Cómo se pasa el parámetro

"in":"query"

dd_query_param(self, k, v)

Nota

Formato para varios pares clave-valor: dd_query_param("key.1","value1");

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

"in":"body" o "in": "formData"

add_body_params(self, k, v)

Nota

Convierta los valores de parámetros que no sean cadenas a cadenas JSON.

Cargar archivos

set_content(self, content)

Nota

Establezca el parámetro content como una matriz 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)

Enviar la solicitud

Invoque do_action_with_exception sobre el client y pase la instancia 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.

Ejemplos

Ejemplo: Invocar una operación de la API de estilo RPC

Invoque la operación DescribeInstanceStatus de Elastic Compute Service (ECS) mediante una llamada genérica de 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()
     

Ejemplo: Invocar una operación de la API de estilo RESTful (ROA)

Invoque la operación DescribeClustersV1 de Container Service for Kubernetes (ACK) mediante una llamada genérica de 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()

Preguntas frecuentes

  1. ¿Qué debo hacer si se devuelve el mensaje de error "Error:MissingParameter The input parameter "AccessKeyId" that is mandatory for processing this request is not supplied"?

    Causa: el AccessKey pair no se configuró correctamente.

    Soluciones:

    1. Compruebe si las variables de entorno ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET están establecidas.

      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%

      Si se devuelve un AccessKey pair válido, las variables de entorno están bien configuradas. Si no se devuelve ningún valor válido, vuelva a configurarlas. Configure environment variables in Linux, macOS, and Windows.

    2. Revise el código en busca de errores relacionados con el AccessKey pair.

      Ejemplo de solicitud con error:

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

      Este error ocurre porque las cadenas que se pasan a os.environ son nombres literales de claves, no credenciales. Establezca ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET como variables de entorno para que os.environ lea los valores correctos.

      Ejemplo de solicitud correcta:

      os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], 
      os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  2. ¿Qué debo hacer si se devuelve el mensaje de error "aliyunsdkcore.acs_exception.exceptions.ServerException: HTTP Status: 400 Error:MissingParameter The input parameter "Timestamp" that is mandatory for processing this request is not supplied"?

    Causa: se estableció uri_pattern para una operación de estilo RPC.

    Solución: elimine uri_pattern de los parámetros de la solicitud.