Distribution

Scheduled Email Sharing

This example shows how to use the Mode API to create an email schedule and subscribe people by adding their emails. You can use this example to create multiple schedules with different parameter values, to add a batch of emails to a schedule, or both.

Endpoints used

.../{workspace}/reports/{report_token}/subscriptions
Supported methods:

  • GET: returns all schedules for the given report
  • POST: creates a new schedule

.../{workspace}/reports/{report_token}/subscriptions/{subscription_token}
Supported methods:

  • GET: returns a schedule
  • PATCH: updates a schedule

.../{workspace}/reports/{report_token}/subscriptions/{subscription_token}/email_memberships
Supported methods:

  • GET: returns all emails subscribed to a given schedule
  • POST: subscribe an email to a schedule
  • PATCH: updates emails subscribed to a schedule

How this example works

In this example, the create_email_schedule method first makes a POST request to app.mode.com/api/{workspace}/reports/{report_token}/subscriptions, creating a schedule. You can specify the time interval, preferences for CSV/PDF/preview/report links, and parameter values in the payload. We then make a GET request to that same endpoint so it returns all schedules for the report. We look at the first schedule on the list, the most recently created one, and get its subscription token. This subscription token lets us add emails to this subscription by making a subsequent POST request to app.mode.com/api/{workspace}/reports/{report_token}/subscriptions/{subscription_token}/email_memberships.

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

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 create_email_schedule(report_token, email):
  #create schedule and set up parameters the schedule should be run with
  url = '%s/api/%s/reports/%s/subscriptions' % (host, ws, report_token)
  headers = {'Content-Type': 'application/json'}
  payload = {'report_subscription': {
               'csv_attachments_enabled':'false',
               'data_previews_enabled': 'true',
               'data_tables_enabled':'false',
               'pdf_attachments_enabled':'false',
               'report_links_enabled':'true',
               'report_schedule':{
                 'cron':{
                   'freq': 'daily',
                   'hour': 14,
                   'time_zone': 'UTC',
                   'day_of_week': 1,
                   'day_of_month': 1,
                   'minute': 0
                 },
                 # params optional
                 'params':{
                   'foo': 'bar'
                 },
                 'timeout':900
               }
             },
             'trk_source':'report'
            }
  r = requests.post(url, headers=headers, auth=HTTPBasicAuth(un, pw), json=payload)
  #get the newest report subscription token and path
  r = requests.get(url, headers=headers, auth=HTTPBasicAuth(un, pw))
  result = r.json()
  subscription_path = result['_embedded']['report_subscriptions'][0]['_links']['self']['href']
  #optional - subscribe an email to the schedule
  subscribe_email(subscription_path, email)

  return

#subscribe an email to the schedule
def subscribe_email(subscription_path, email):
  url = '%s%s/email_memberships' % (host, subscription_path)
  headers = {'Content-Type': 'application/json'}
  payload = {'membership': {'subscriber_email': email}, 'trk_source':'report'}
  r = requests.post(url, headers=headers, auth=HTTPBasicAuth(un, pw), json=payload)
  return r.status_code



create_email_schedule('report_token', 'email_address')
const request = require('request-promise');

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

const createEmailSchedule = async (reportToken, email) => {
  // create schedule and set up parameters the schedule should be run with
  const reportSubscription = {
    report_subscription: {
      csv_attachments_enabled: false,
      data_previews_enabled: true,
      data_tables_enabled: false,
      pdf_attachments_enabled: false,
      report_links_enabled: true,
      report_schedule: {
        cron: {
          freq: 'daily',
          hour: 14,
          time_zone: 'UTC',
          day_of_week: 1,
          day_of_month: 1,
          minute: 0
        },
        // params optional
        params: {
          'foo': 'bar'
        },
        timeout: 900,
      },
    },
    trk_source: 'report',
  };
  const res = await request({
    method: 'POST',
    url: `${host}/api/${ws}/reports/${reportToken}/subscriptions`,
    auth: { username, password },
    json: true,
    body: reportSubscription,
  });
  // get the newest report subscription token and path
  const subscriptions = await request({
    url: `${host}/api/${ws}/reports/${reportToken}/subscriptions`,
    auth: { username, password },
    json: true,
  });
  const subscriptionPath = subscriptions._embedded.report_subscriptions[0]._links.self.href;
  // optional - subscribe an email to the schedule
  return await subscribeEmail(subscriptionPath, email);
};

// subscribe an email to the schedule
const subscribeEmail = async (subscriptionPath, email) => {
  const payload = {
    membership: { subscriber_email: email },
    trk_source: 'report',
  };
  return await request({
    method: 'POST',
    url: `${host}${subscriptionPath}/email_memberships`,
    auth: { username, password },
    json: true,
    body: payload,
  }).status_code;
};

createEmailSchedule('reportToken', 'emailAddress');