Tüm Ürünler
Search
Belge Merkezi

Alibaba Cloud SDK:Genel çağrılar

Son Güncelleme:Oct 07, 2026

Alibaba Cloud SDK for Java V2.0, hizmete özgü SDK'ları yüklemenize gerek kalmadan herhangi bir OpenAPI işlemini çağırmanıza olanak tanıyan genel API çağrılarını destekler.

Özellikler

Hafif: Yalnızca Alibaba Cloud SDK'nın çekirdek kitaplığını yükleyerek Alibaba Cloud SDK V2.0 for Python ile API işlemlerini çağırabilir, her hizmet için ayrı SDK yüklemenize gerek kalmaz.

Kullanımı kolay: Yalnızca ortak istek parametrelerini oluşturup genel bir istemci kullanarak istek başlatmanız yeterlidir. Yanıtlar ortak biçimlerde döner.

Daha fazla bilgi için bkz. Genel çağrılar ve özel çağrılar.

Kullanım notları

Genel bir çağrı yapmadan önce API stilini, istek parametrelerini ve URL'yi elde etmek için API işleminin meta verilerini görüntülemenizi öneririz.

Alibaba Cloud SDK'nın çekirdek kitaplığını yükleyin

Python için Alibaba Cloud SDK V2.0'ın çekirdek kitaplığını yüklemek üzere terminalinizde aşağıdaki komutu çalıştırın:

pip install alibabacloud-tea-openapi

Bir API işlemini çağırın

1. İstek istemcisini başlatın

alibabacloud_tea_openapi paketindeki client modülünden bir Client sınıfı oluşturarak istek istemcisini başlatın. OpenAPI çağrıları yapmak için bu istemciyi kullanın. İstemciyi başlatırken Credentials aracını da kullanabilirsiniz. Credentials aracı hakkında daha fazla bilgi için bkz. Erişim kimlik bilgilerini yönetin.

Önemli

İstemci örneği iş parçacığı güvenlidir. Uygulamanızda istemciyi oluşturmak için singleton desenini kullanın. Bu sayede uygulama yaşam döngüsü boyunca aynı kimlik bilgisi ve uç nokta için yalnızca bir istemci örneği başlatılır.

import os

from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_openapi.client import Client as OpenApiClient

# Obtain the AccessKey pair from environment variables.
config = open_api_models.Config(
  access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
  access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# Set the service endpoint.
config.endpoint = f'ecs-cn-hangzhou.aliyuncs.com'
# config.protocol = 'HTTPS' # Send requests over HTTPS.
# config.http_proxy = 'http://127.0.0.1:9898'
# config.https_proxy='http://user:password@127.0.0.1:8989'
# config.read_timeout = 10000,  # Read timeout period in milliseconds (ms).
# config.connect_timeout = 5000  # Connection timeout period in milliseconds (ms).
client = OpenApiClient(config)

# Use the Credentials tool.
# crendconfig = credentialConfig()
# crendconfig.type = 'access_key'
# crendconfig.access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
# crendconfig.access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
# 
# credentialsClient = CredClient(crendconfig)
# config = open_api_models.Config()
# config.credential = credentialsClient
# config.endpoint = f'ecs.cn-hangzhou.aliyuncs.com'
# client = OpenApiClient(config)

2. OpenAPI bilgilerini yapılandırın

API stili, API sürümü ve istek yöntemi gibi temel OpenAPI bilgilerini yapılandırmak için alibabacloud_tea_openapi paketindeki models modülünden Params sınıfını kullanın. Aşağıdaki örnek, DescribeInstanceTypeFamilies işleminin nasıl çağrılacağını gösterir:

params = open_api_models.Params(
  style='RPC',  # API style: RPC or ROA.
  version='2014-05-26',  # API version number.
  action='DescribeInstanceTypeFamilies',  # API name.
  method='POST',  # Request method.
  pathname='/',  # API resource path. The default path for RPC APIs is "/". For ROA APIs, get the resource path from data.path in the OpenAPI metadata.
  protocol='HTTPS',  # Request protocol: HTTPS or HTTP. We recommend that you use HTTPS.
  auth_type='AK',  # Authentication type. The default value is used. If the OpenAPI supports anonymous requests, you can pass Anonymous to make an anonymous request.
  req_body_type='json',  # Request body type. Supported types are byte, json, and formData.
  body_type='json'  # Response data format. json is supported.
)

3. İstek parametrelerini yapılandırın

İstek parametrelerini yapılandırmak için alibabacloud_tea_openapi paketindeki models modülünden OpenApiRequest sınıfını kullanın. Parametreleri sorgu, gövde veya akış üzerinden iletebilirsiniz. Meta verilerdeki bilgilere göre yöntem seçin. Örneğin, DescribeInstanceTypeFamilies işleminin RegionId istek parametresi meta verilerde {"name":"RegionId","in":"query",...}} olarak belirtilmiştir. "in":"query" ifadesi, RegionId'nin bir sorgu parametresi olarak iletildiğini gösterir.


Parametrenin iletilme yöntemi


Açıklama


query


İstek parametresi "in":"query" değerini gösteriyorsa parametreyi sorgu üzerinden iletin.


body


İstek parametresi "in":"body" veya "in": "formData" değerini gösteriyorsa parametreyi gövdede iletin. Parametreleri istek gövdesinde iletirken reqBodyType değerini gövde türüne göre ayarlayın.


stream


Dosya yüklemek için Stream parametresini yapılandırarak dosya akışlarını iletebilirsiniz.

from alibabacloud_openapi_util.client import Client as OpenApiUtilClient

# Scenario 1: Set query parameters.
query = {'RegionId': 'cn-hangzhou'}
# Create an API request object.
request = open_api_models.OpenApiRequest(
  query=OpenApiUtilClient.query(query),
)

# Scenario 2: Set body parameters. The value of reqBodyType is json.
# body = {
#  'param1': 'value1'
# }
# Create an API request object.
# request = open_api_models.OpenApiRequest(
#     body=OpenApiUtilClient.query(body),
# )

# Scenario 3: Use a stream parameter to pass a file stream.
# Create an API request object.
# request = open_api_models.OpenApiRequest(
#     stream='<FILE_STREAM>', # Replace <FILE_STREAM> with the actual file stream.
# )

# Scenario 4: Set body parameters. The value of reqBodyType is formData.
# form_data = {
#  'param1': 'value1'
# }
# Create an API request object.
# request = open_api_models.OpenApiRequest(
#     body=form_data,
# )
        

4. İsteği gönderin

1. Adımda oluşturulan client nesnesini kullanarak senkron istek için call_api veya eşzamansız istek için call_api_async yöntemini çağırın. Zaman aşımı ve proxy yapılandırmaları gibi geçerli isteğe yönelik çalışma zamanı parametrelerini de ayarlayabilirsiniz. Daha fazla bilgi için bkz. Gelişmiş yapılandırmalar.

from alibabacloud_tea_util import models as util_models

# Runtime configurations, which take effect only for the current request.
runtime = util_models.RuntimeOptions(
  # ignore_ssl=True  # Ignores SSL certificate verification. Verification is enabled by default.
  # autoretry=True,  # Specifies whether to enable retries. Default: disabled. 
  # max_attempts=3  # Number of retries. Default: 3.
)
# Synchronous call.
response = client.call_api(params, request, runtime)
# Asynchronous call.
# response = await client.call_api_async(params, request, runtime)

# The return value is a dict. You can get three types of data from the result: body, headers, and statusCode (the HTTP status code).
print(response['body'])

Örnek kod

Örnek: RPC tarzı bir API işlemini çağırın

Aşağıdaki örnek, ECS DescribeInstanceTypeFamilies işlemine genel bir çağrı yapar.

import os

from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient

class Sample:
  @staticmethod
  def main():
    # Obtain the AccessKey pair from environment variables.
    config = open_api_models.Config(
      access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
    # Set the service endpoint.
    config.endpoint = f'ecs-cn-hangzhou.aliyuncs.com'
    client = OpenApiClient(config)
    params = open_api_models.Params(
      style='RPC',  # API style.
      version='2014-05-26',  # API version number.
      action='DescribeInstanceTypeFamilies',  # API name.
      method='POST',  # Request method.
      pathname='/',  # API PATH. The default path for RPC APIs is "/".
      protocol='HTTPS',  # API protocol.
      auth_type='AK',
      req_body_type='json',  # Request body content format.
      body_type='json'  # Response body content format.
    )

    query = {'RegionId': 'cn-hangzhou'}
    # Create an API request object.
    request = open_api_models.OpenApiRequest(
      query=OpenApiUtilClient.query(query),
    )
    # Create a runtime options object.
    runtime = util_models.RuntimeOptions()
    # Call the API and print the response.
    response = client.call_api(params, request, runtime)
    # The return value is a Map. You can get three types of data from the Map: body, headers, and statusCode (the HTTP status code).
    print(response)

  @staticmethod
  async def main_async():
    """
        The asynchronous main function, which shows how to call an Alibaba Cloud API asynchronously.
        """
    # Obtain the AccessKey pair from environment variables.
    config = open_api_models.Config(
      access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
    # Set the service endpoint.
    config.endpoint = f'ecs-cn-hangzhou.aliyuncs.com'
    client = OpenApiClient(config)
    params = open_api_models.Params(
      style='RPC',  # API style.
      version='2014-05-26',  # API version number.
      action='DescribeInstanceTypeFamilies',  # API name.
      method='POST',  # Request method.
      pathname='/',  # API PATH.
      protocol='HTTPS',  # API protocol.
      auth_type='AK',
      req_body_type='json',  # Request body content format.
      body_type='json'  # Response body content format.
    )

    query = {'RegionId': 'cn-hangzhou'}
    # Create an API request object.
    request = open_api_models.OpenApiRequest(
      query=OpenApiUtilClient.query(query),
    )
    # Create a runtime options object.
    runtime = util_models.RuntimeOptions()
    # Make an asynchronous API call.
    await client.call_api_async(params, request, runtime)

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

Örnek: RESTful tarzı (ROA tarzı) bir API işlemini çağırın

Aşağıdaki örnek, ACK DescribeClustersV1 işlemine genel bir çağrı yapar.

import os

from alibabacloud_openapi_util.client import Client as OpenApiUtilClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_util import models as util_models

class Sample:
  @staticmethod
  def main() -> None:
    # Obtain the AccessKey ID and AccessKey secret from environment variables.
    config = open_api_models.Config(
      access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
    config.endpoint = f'cs.cn-qingdao.aliyuncs.com'
    client = OpenApiClient(config)
    params = open_api_models.Params(
      # API name.
      action='DescribeClustersV1',
      # API version.
      version='2015-12-15',
      # API protocol.
      protocol='HTTPS',
      # API HTTP method.
      method='GET',
      auth_type='AK',
      style='ROA',
      # API PATH. For ROA APIs, get the resource path from data.path in the OpenAPI metadata.
      pathname=f'/api/v1/clusters',
      # Request body content format.
      req_body_type='json',
      # Response body content format.
      body_type='json'
    )
    # query params
    queries = {'name': 'cluster-demo'}
    request = open_api_models.OpenApiRequest(
      query=OpenApiUtilClient.query(queries)
    )
    # runtime options
    runtime = util_models.RuntimeOptions()
    # The return value is a Map. You can get three types of data from the Map: the response body, response headers, and the HTTP status code.
    response = client.call_api(params, request, runtime)
    print(response)

  @staticmethod
  async def main_async() -> None:
    # Obtain the AccessKey ID and AccessKey secret from environment variables.
    config = open_api_models.Config(
      access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
    config.endpoint = f'cs.cn-qingdao.aliyuncs.com'
    client = OpenApiClient(config)
    params = open_api_models.Params(
      # API name.
      action='DescribeClustersV1',
      # API version.
      version='2015-12-15',
      # API protocol.
      protocol='HTTPS',
      # API HTTP method.
      method='GET',
      auth_type='AK',
      style='ROA',
      # API PATH.
      pathname=f'/api/v1/clusters',
      # Request body content format.
      req_body_type='json',
      # Response body content format.
      body_type='json'
    )
    # query params
    queries = {'name': 'cluster-demo'}
    request = open_api_models.OpenApiRequest(
      query=OpenApiUtilClient.query(queries)
    )
    # runtime options
    runtime = util_models.RuntimeOptions()
    # The return value is a Map. You can get three types of data from the Map: the response body, response headers, and the HTTP status code.
    await client.call_api_async(params, request, runtime)

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