You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程从GCP获取项目计费信息?求可用API方案

解决方案:GCP动态获取计费与定价数据的API

嘿,我刚好之前处理过类似的需求,你找的应该是这几个专门的API,分两种场景来说:

1. 获取GCP服务的定价数据(单价、SKU信息)

你提到的getBillingInfo这类API确实只返回账户关联信息,而要获取实时定价数据,GCP提供了Cloud Billing Catalog API——这是专门用来查询所有GCP服务的SKU、定价规则、区域价格的官方API,完全支持编程调用,不用依赖文件导出。

核心功能:

  • 查询全量GCP服务的定价目录
  • 过滤特定服务(比如Compute Engine、Cloud Storage)、区域、计费模式(按需、预留实例)的价格
  • 获取详细定价规则(比如阶梯定价、折扣信息)

示例用法:

REST API请求

GET https://cloudbilling.googleapis.com/v1/catalog/services?filter="displayName:~'Compute Engine'"

这个请求会返回所有和Compute Engine相关的服务SKU及对应定价信息。

Python客户端库示例

from google.cloud import billing_v1

def get_gcp_storage_pricing():
    client = billing_v1.CloudBillingCatalogClient()
    # 过滤只查询Cloud Storage的定价
    request = billing_v1.ListServicesRequest(
        filter="displayName='Cloud Storage'"
    )
    response = client.list_services(request)
    
    for service in response:
        print(f"服务名称: {service.display_name}")
        # 遍历该服务下的所有SKU
        for sku in service.skus:
            print(f"  SKU ID: {sku.sku_id}")
            # 提取USD计价的单价信息
            for pricing_info in sku.pricing_info:
                if pricing_info.pricing_expression.tiered_rates:
                    unit_price = pricing_info.pricing_expression.tiered_rates[0].unit_price
                    print(f"    单价: {unit_price.units}.{unit_price.nanos} USD")

2. 获取项目的实际计费/使用数据

如果你的需求是获取自己项目已产生的费用或资源使用量,而不是官方定价,那可以用Cloud Billing Usage API,或者结合Cloud Billing Budget API来获取费用统计和预测。

Cloud Billing Usage API

这个API可以直接查询项目的资源使用量数据,你可以结合Catalog API的定价数据计算实际费用,也能获取聚合后的费用信息。

示例:查询项目月度使用数据

GET https://cloudbilling.googleapis.com/v1/projects/[你的项目ID]/billingInfo/usage?startTime=2024-01-01T00:00:00Z&endTime=2024-01-31T23:59:59Z

注意事项

  • 调用这些API需要对应的IAM权限,比如billing.catalogs.get(针对Catalog API)、billing.usage.read(针对Usage API),需要给服务账号或用户分配相应角色。
  • 所有API都支持GCP官方客户端库(Python、Java、Go等),也可以直接用REST或gcloud命令行调用。

内容的提问来源于stack exchange,提问作者Ravi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:02:57