How do I get an API response in CSV format instead of JSON?
search cancel

How do I get an API response in CSV format instead of JSON?

book

Article ID: 283634

calendar_today

Updated On:

Products

CloudHealth

Issue/Introduction

Currently, all API responses return JSON.  If you would like the output to be in CSV, the JSON will need to be converted.  The steps to achieve this are the following: 

  1. Add your API key to the below script and save
  2. Open up terminal   
  3. Change to the directory were the script is saved 
  4. Run `python APIExample.py >> api.csv` which will make a new file called api.csv in the same directory

NOTE:  Be aware that the script below is provided as an example and comes with no guarantee to work in your environment.  As such, troubleshooting this code is not supported.

 

Raw sample script provided below:

#!/usr/bin/env python

import urlparse
import urllib2
import json

API_ENDPOINT = "https://chapi.cloudhealthtech.com/olap_reports/"
API_KEY = "<your api key>"

# Returns json for requested report.
def get_report(report, api_key):
  uri = urlparse.urljoin(API_ENDPOINT, report)
  uri += "?api_key=%s" % API_KEY
  request  = urllib2.Request(uri, headers={"Accept" : "application/json"})
  response = urllib2.urlopen(request)
  page = response.read()
  return json.loads(page)

# Fetch the json for the report
try:
  data = get_report("cost/history", API_KEY)

  # Get list of dimension names
  dimensions = [dim.keys()[0] for dim in data["dimensions"]]

  # Output a CSV for this report
  print "Month,%s" % ",".join( [member["label"] for member in data['dimensions'][1][dimensions[1]]])
  index = 0
  for month in data["dimensions"][0][dimensions[0]]:
    row = data['data'][index]
    if row == None:
      continue

    # We have only selected 1 measure so just take first element of every array
    row_as_array = [str(item[0]) for item in row]
    print "%s,%s" % (month["label"], ",".join(row_as_array))
    index+=1

except urllib2.HTTPError as e:
  print e.code
  print e.read()

Attachments

APIExample.py get_app