The Azure REST API allows you to use the Python requests library to get information from IoT Hub in the form of an HTTP request. An HTTP request is the source of the total cost information for the dashboard.

Bearer Token

To make a GET HTTP request using the Azure REST API, you need a Bearer token to be included in the header for the request. The Bearer token is only viable for one hour. In order to always be sure you have a valid token, the Azure CLI is run using the Popen() function from the subprocess Python library.

The subprocess library allows for terminal commands to be run in the background. The output from the terminal can be brought into the Python script. In this case, az account get-access-token is run and its output is converted to a JSON feed. The 'accessToken' JSON item contains the Bearer token and is added to headers.

output = Popen(['az', 'account', 'get-access-token'], stdout=PIPE)
#  parses the output into a json and grabs the bearer token
bear = json.loads(output.communicate()[0].decode('utf-8').strip())
#  creates headers to include with GET HTTP request for cost data
headers = {'Authorization': 'Bearer ' + bear['accessToken'], 'Content-Type': 'application/json'}

The URL request needs your subscription ID added to it. This is accomplished using .format() and inserting {} in the required location of the URL for the subscription ID. The url and headers are packed into a requests.get() function that is returned as a JSON feed with response.json(). cost holds the 'costInBillingCurrency' JSON item that has the daily cost for your cloud services.

#  updates request URL with your subscription ID
url = "{}/providers/Microsoft.Consumption/usageDetails?api-version=2021-10-01".format(subscription_id)
#  makes HTTP request
response = requests.get(url, headers=headers)
#  packs the HTTP response into a JSON
feed = response.json()
#  grabs the cost per day from the JSON feed
cost = feed['value'][cost_json_index]['properties']['costInBillingCurrency']

This guide was first published on Aug 23, 2022. It was last updated on Apr 21, 2024.

This page (Using the Azure REST API) was last updated on Mar 08, 2024.

Text editor powered by tinymce.