简体   繁体   中英

IBM Cloud: How to access the API for billing and usage?

How can I retrieve usage and cost data for my IBM Cloud account using a REST API? I found that there are billing related commands and I can export some data as JSON . Is there an API or SDK I can use, ideally Python?

Here are some of the IBM Cloud billing commands I use:

ibmcloud billing resource-instances-usage --json

ibmcloud billing  account-usage --json

Are there equivalent APIs for that?

I couldn't find a documented API but used the tracing to see how the above commands are executed. Using a valid access_token a program can call the metering host and obtain usage data for an account, resource group or all resource instances:

A GET on the following URL with an account ID and month as YYYY-MM returns a JSON object with all resource usage and related cost:

https://metering-reporting.ng.bluemix.net/v4/accounts/account_id/resource_instances/usage/?_limit=100&_names=true

I coded up a small Python script that dumps that data or prints it as CSV .

def processResourceInstanceUsage(account_id, billMonth):
    METERING_HOST="https://metering-reporting.ng.bluemix.net"
    USAGE_URL="/v4/accounts/"+account_id+"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"

    url=METERING_HOST+USAGE_URL
    headers = {
        "Authorization": "{}".format(iam_token),
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
    response=requests.get(url, headers=headers)
    print ("\n\nResource instance usage for first 100 items")
    return response.json()

The GitHub repo openwhisk-cloud-usage-samples uses a serverless approach to getting data via APIs. Examples are included in the repo. It's written in Javascript, but a package it uses openwhisk-jsonetl was designed so that you could declare the URLs and parameters in YAML (rather than writing code) to request and transform JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM