Export CSV

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

Endpoints used

Supported method:

  • GET: returns a report’s historic runs

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 app.mode.com/api/{workspace}/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 app.mode.com/api/{workspace}/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 the API token, API secret, Workspace name, and other custom information as needed. Follow these steps to create an API token.
  • 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'
ws = 'workspace_name' # Note: workspace_name value should be all lowercase
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, ws, 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):
        return r
      print ('Report latest run did not succeed. Take a look at the report details.')


def get_report_latest_run_status(report_token):
  url = '%s/api/%s/reports/%s/runs' % (host, ws, 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}

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

const host = 'https://modeanalytics.com';
const ws = 'workspaceName'; // Note: workspaceName value should be all lowercase
const username = 'apiToken';
const password = 'apiSecret';

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

  if (state === "succeeded") {
      url: `${host}/api/${ws}/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.'))