Through the Python SDK alibabacloud_bssopenapi20171214 call the Alibaba Cloud BSS OpenAPI to query instance-level bills under the current account.
Prerequisite check (must be performed first)
Before executing any query, you must first confirm that AK/SK has been configured.
From the current working directory's .env file read:
Check whether the following exists in the current working directory: .env file:
find . -maxdepth 1 -name ".env" -exec cat {} \;
.env file format:
ALIBABA_CLOUD_ACCESS_KEY_ID=your-access-key-id
ALIBABA_CLOUD_ACCESS_KEY_SECRET=your-access-key-secret
Load in Python code:
from dotenv import load_dotenv
import os
load_dotenv() # 从当前工作目录的 .env 文件加载
access_key_id = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID")
access_key_secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
Or through environment variables:
export ALIBABA_CLOUD_ACCESS_KEY_ID="your-access-key-id"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="your-access-key-secret"
If the credential check is not passed, the query steps should not continue.
Install dependencies
pip install alibabacloud_bssopenapi20171214 alibabacloud_credentials alibabacloud_tea_openapi alibabacloud_tea_util python-dotenv
Request parameters
Required parameters
| Parameter | Type | Description |
|---|---|---|
| BillingCycle | string | Billing period, in YYYY-MM format, only the most recent 18 months are supported, e.g. 2024-03 |
Optional parameters (filter conditions)
| Parameter | Type | Description |
|---|---|---|
| ProductCode | string | Product code, e.g. rds、ecs |
| ProductType | string | Product type, required when ProductCode is a cloud marketplace product |
| SubscriptionType | string | Subscription type:Subscription(prepaid) / PayAsYouGo(postpaid) |
| IsBillingItem | boolean | Whether to retrieve by billing item dimension, default false |
| Granularity | string | Bill granularity:MONTHLY(monthly) / DAILY(daily), BillingDate must be specified when DAILY is selected |
| BillingDate | string | Billing date, in YYYY-MM-DD format, required only when Granularity=DAILY |
| IsHideZeroCharge | boolean | Whether to hide zero-fee bills, default false |
| BillOwnerId | integer | Resource owner account ID |
Pagination parameters (SDK uses the NextToken method)
| Parameter | Type | Description |
|---|---|---|
| MaxResults | integer | Number per page, maximum 300 |
| NextToken | string | Next page token, empty for the first request, subsequently use the NextToken from the previous response |
Response structure
response.body.data = {
"NextToken": "xxx", # 下一页的令牌(如果没有更多数据则不返回)
"MaxResults": 300, # 每页数量
"TotalCount": 100, # 总记录数
"BillingCycle": "2024-03",
"Items": {
"Item": [...] # 账单详情列表
}
}
Retrieve complete data with pagination
Pagination logic must be implemented, because a single API call returns at most 300 records.
Pagination rules
- First request: do not specify
NextTokenor set to an empty string - Subsequent requests: use the value of
response.body.data.next_tokenfrom the previous response - Termination condition:
next_tokenin the response is empty or does not exist (indicating all data has been retrieved)
Example code for paginated retrieval
def fetch_all_bills(client, billing_cycle, max_results=300, **filter_kwargs):
"""获取指定账期的所有账单记录(自动分页)"""
all_items = []
next_token = None
while True:
request = bss_open_api_20171214_models.DescribeInstanceBillRequest(
billing_cycle=billing_cycle,
max_results=max_results,
next_token=next_token,
**filter_kwargs
)
response = client.describe_instance_bill_with_options(request, util_models.RuntimeOptions())
if not response.body.success or not response.body.data.items.item:
break
items = response.body.data.items
all_items.extend(items)
# 判断是否还有更多数据
next_token = getattr(response.body.data, 'next_token', None)
if not next_token:
break
return all_items
DescribeInstanceBill usage
Core process:
- From environment variables (or the current working directory's
.env) readALIBABA_CLOUD_ACCESS_KEY_ID/ALIBABA_CLOUD_ACCESS_KEY_SECRET - Create
BssOpenApi20171214Client - Build request parameters according to query conditions (including filter conditions and pagination parameters)
- Implement pagination logic, call in a loop until complete data is retrieved
- Aggregate and process all bill records
Reference implementation
reference/ The directory contains Agent reference samples, not directly runnable scripts. An agent using this skill should refer to the structure and API call methods of these codes to generate an implementation suitable for its own context.
Agent usage:
- Read
reference/describe_instance_bill.pyto understand the API call patterns - Generate the corresponding implementation code based on the current project structure
- Do not copy and run directly; use it as a reference template
Core API Call Patterns:
from alibabacloud_bssopenapi20171214.client import Client as BssOpenApi20171214Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_bssopenapi20171214 import models as bss_open_api_20171214_models
# 1. 创建客户端
config = open_api_models.Config(
access_key_id=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"),
access_key_secret=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
)
config.endpoint = 'business.aliyuncs.com'
client = BssOpenApi20171214Client(config)
# 2. 调用 API(单次调用,带分页参数)
request = bss_open_api_20171214_models.DescribeInstanceBillRequest(
billing_cycle="2024-03",
max_results=300,
next_token=None, # 首次请求设为 None,后续使用响应中的 next_token
product_code="ecs", # 可选筛选条件
)
response = client.describe_instance_bill_with_options(request, util_models.RuntimeOptions())
Common Query Scenarios
Scenario 1: Query all bills for a given month
all_items = fetch_all_bills(client, billing_cycle="2024-03", max_results=300)
Scenario 2: Query bills for a specified product
all_items = fetch_all_bills(
client,
billing_cycle="2024-03",
max_results=300,
product_code="rds"
)
Scenario 3: Query post-paid product bills
all_items = fetch_all_bills(
client,
billing_cycle="2024-03",
max_results=300,
subscription_type="PayAsYouGo"
)
Scenario 4: Query bills by day
all_items = fetch_all_bills(
client,
billing_cycle="2024-03",
max_results=300,
granularity="DAILY",
billing_date="2024-03-15"
)
Error Handling Recommendations
401/403: AK/SK is invalid, not configured, or RAM permissions are insufficientInvalidAccessKeyId: AccessKeyId is incorrectSignatureDoesNotMatch: AccessKeySecret is incorrect or the signature does not match- If the exception contains the
Recommendfield, troubleshoot preferentially using the diagnostic link
Usage Workflow
- Check the
.envfile or environment variables in the current working directory to confirm that AK/SK is configured - Install dependencies
- Read
reference/describe_instance_bill.pyto understand the API call patterns - Build request parameters according to the query requirements (filter conditions + pagination parameters)
- Implement the pagination loopto obtain the complete bill data
- Aggregate and process all bill records
Notes
BillingCycleThe parameter format isYYYY-MM(e.g.,2024-03), and it must be provided when calling- Pagination logic must be implemented, and a single call returns at most 300 records
- Pagination uses the
NextTokenmethod: for the first request usenext_token=None, and subsequently use thenext_tokenvalue from the response - Pagination termination condition:
next_tokenin the response is empty or does not exist - Filter conditions:
product_code、subscription_type、granularity, etc. can effectively reduce the amount of returned data - The reference code is a sample used to help the agent understand how to call the API
- The agent should generate code according to actual requirements, including error handling, parameter passing, etc.