Distribution

Export CSV

You can use the Mode API to automate the process of exporting reports to CSVs.

Endpoints used

.../{organization}/reports/{report_token}/runs
Supported method:

  • GET: returns a report’s historic runs

.../{organization}/reports/{report_token}/runs/{run_token}/results/content.csv
Supported method:

  • GET: downloads a report run’s results to CSV

How this example works

In this example, the export_report_to_csv method first calls the helper function get_report_latest_run_status to get the run token and the latest report run’s state. get_report_latest_run_status makes a GET request to modeanalytics.com/api/{organization}/reports/{report_token}/runs and retrieves the first in the list of historic runs. Back in the method export_report_to_csv, we check whether the latest run was successful. If it was, we make a GET request to modeanalytics.com/api/{organization}/reports/{report_token}/runs/{run_token}/results/content.csv to download the CSV of the latest run to the directory where the .py file is. If the latest run fails, we print an error message in the console.

To try it yourself

  • Download the example code to a .py file
  • Input your API token, API secret, organization name, and other custom information as needed. API token and secret can be generated here
  • Save the .py file in your desired directory
  • Open the terminal and navigate to that directory
  • Run the command python3 {file_name}.py
  • All of our Python recipes require Python 3
import json
import requests
import cgi, cgitb

from requests.auth import HTTPBasicAuth

host = 'https://modeanalytics.com'
org = 'org_name'
un = 'api_token'
pw = 'api_secret'

def export_report_to_csv(report_token):
  latest_report_run = get_report_latest_run_status(report_token)
  status = latest_report_run['status']
  most_recent_report_run_token = latest_report_run['most_recent_report_run_token']

  if status == "succeeded":
    url = '%s/api/%s/reports/%s/runs/%s/results/content.csv' % (host, org, report_token, most_recent_report_run_token)
    r = requests.get(url, auth=HTTPBasicAuth(un, pw))

    params = cgi.parse_header(r.headers['Content-Disposition'])[1]
    file_name = params['filename']
    if r.status_code == 200:
      with open(file_name, 'wb') as f:
        for chunk in r.iter_content(1024):
          f.write(chunk)
        return r
    else:
      print ('Report latest run did not succeed. Take a look at the report details.')

  return


def get_report_latest_run_status(report_token):
  url = '%s/api/%s/reports/%s/runs' % (host, org, report_token)
  r = requests.get(url, auth=HTTPBasicAuth(un, pw))
  result = r.json()
  most_recent_report_run_token = result['_embedded']['report_runs'][0]['token']
  status = result['_embedded']['report_runs'][0]['state']
  return {'status':status, 'most_recent_report_run_token' : most_recent_report_run_token}

export_report_to_csv('report_token')
const request = require('request');
const fs = require('fs');

const host = 'https://modeanalytics.com';
const org = 'orgName';
const username = 'apiToken';
const password = 'apiSecret';

const exportReportToCSV = reportToken => request({
  url: `${host}/api/${org}/reports/${reportToken}/runs`,
  json: true,
  auth: { username, password },
}, (err, res, body) => {
  let {
    state,
    token: mostRecentReportRunToken,
  } = body._embedded.report_runs[0];

  if (state === "succeeded") {
    request({
      url: `${host}/api/${org}/reports/${reportToken}/runs/${mostRecentReportRunToken}/results/content.csv`,
      auth: { username, password },
      gzip: true,
    })
      .on('error', err => console.error('Report\'s latest run failed. Please fix the queries errors before exporting again.'))
      .pipe(fs.createWriteStream('mode-report.csv'));
    }
  return;
});

exportReportToCSV('reportToken');