API签名指南-Python:请求签名与API调用

时间:2024-05-15 14:57:57

请求签名与API调用

  1. 在命令行中,使用pip安装“requests”库。

    1
    pip install requests
    

  2. 在工程中引入apig_sdk。

    1
    2
    from apig_sdk import signer
    import requests
    

  3. 生成一个新的Signer,填入AK和SK。

    1
    2
    3
    4
    5
    6
    sig = signer.Signer()
    # Set the AK/SK to sign and authenticate the request.
    # Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables.
    # In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
    sig.Key = os.getenv('HUAWEICLOUD_SDK_AK')
    sig.Secret = os.getenv('HUAWEICLOUD_SDK_SK')
    

  4. 生成一个新的Request,指定域名、方法名、请求uri和body。

    以虚拟私有云服务的查询VPC列表接口为例,HTTP方法为GET,域名(Endpoint)为service.region.example.com,请求URI:/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs?limit=1
    1
    2
    3
    # The following example shows how to set the request URL and parameters to query a VPC list.
    r = signer.HttpRequest("GET", "https://{service}.region.example.com/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs?limit=1")
    # r.body = "{\"a\":1}"
    

  5. 添加需要签名的请求消息头,或者其他用途的头域,如多项目场景中添加X-Project-Id,或者全局服务场景中添加X-Domain-Id。如果添加多个请求消息头,使用英文逗号分隔。

    1
    r.headers = {"X-Project-Id": "xxx"}
    

  6. 进行签名,执行此函数会在请求参数中添加用于签名的X-Sdk-Date头和Authorization头。

    1
    sig.Sign(r)
    
    • X-Sdk-Date是一个必须参与签名的请求消息头参数。
    • 您无需关注哪些消息头参数参与了签名,由SDK自行完成。

  7. 访问API,查看访问结果。

    1
    2
    3
    resp = requests.request(r.method, r.scheme + "://" + r.host + r.uri, headers=r.headers, data=r.body)
    print(resp.status_code, resp.reason)
    print(resp.content)
    

support.huaweicloud.com/devg-apisign/api-sign-sdk-python.html