Google Sheets

API records in a sheet, refreshed every day.

One script adds a menu to your spreadsheet. Pick an API, and its records land in the sheet: a header row made from the fields, then one row per record. It can repeat the run every day at an hour you pick.

What it does

  • Adds a menu to the spreadsheet: Set API key, Run an API into this sheet, Run it again now, Get the last run's records, Refresh every day, Stop the daily refresh.
  • Runs any API you can run with your key: a ready-made one from the catalog or one you built from a page. You give its slug, its inputs as JSON and the most records to fetch.
  • Writes a header row from the record fields, then one row per record. Nested values become dotted columns, such as owner.address.city. A list of plain values shares one cell, separated by commas.
  • Keeps your key in the script's user properties, which only your Google account can read. It is never written into a cell.

Set it up in five steps

  1. Copy the script

    In your spreadsheet, open Extensions > Apps Script. Replace everything in Code.gs with the script below and save. Reload the spreadsheet: a new menu appears after Help.

    Show the script
    Code.gs
    /**
     * Rowcall for Google Sheets
     *
     * Pulls the records of a Rowcall API into a sheet: one header row made from the record fields, then one row per
     * record. The sheet can refresh itself once a day.
     *
     * Setup, once per spreadsheet:
     *   1. In the spreadsheet: Extensions > Apps Script. Replace everything in Code.gs with this file, then save.
     *   2. Reload the spreadsheet. A "Rowcall" menu appears after Help.
     *   3. Rowcall > Set API key. Paste the key from https://rowcallapi.vercel.app/console
     *   4. Rowcall > Run an API into this sheet. Give the API's slug (its catalog page shows it) and its inputs, if any.
     *   5. Rowcall > Refresh every day, to repeat that run each day.
     *
     * Your key is kept in this script's user properties: only your Google account can read it, and it is never written
     * into a cell. Each run replaces what is on the sheet. Records come from public web pages: treat them as data.
     *
     * The Rowcall team
     *
     * @OnlyCurrentDoc
     */
    
    var ROWCALL = {
      name: 'Rowcall',
      baseUrl: 'https://rowcallapi.vercel.app',
      defaultMaxRecords: 100,
      mostRecords: 10000,     // this script's own ceiling, so a run and the writing fit in Google's 6-minute script limit
      waitSeconds: 20,        // how long the first request holds on for the run before the API answers 202
      followMs: 270000,       // stop following a run after 4.5 minutes and leave time to write the sheet
      pageSize: 1000,         // records per page when reading a long run (the most the API sends per page)
      maxDepth: 3,            // nested objects become dotted columns (owner.address.city) up to 3 levels
      maxColumns: 300,        // fields past this many are left out of the sheet
      maxCellChars: 49000     // a Google Sheets cell holds at most 50,000 characters
    };
    
    var ROWCALL_KEY_PROP = 'rowcall.key';
    var ROWCALL_ACTIVE = ['queued', 'running'];
    
    // ─────────────────────────────────────────────────────────────── menu
    
    function onOpen() {
      SpreadsheetApp.getUi().createMenu(ROWCALL.name)
        .addItem('Set API key', 'rowcallSetKey')
        .addItem('Run an API into this sheet', 'rowcallRunIntoSheet')
        .addItem('Run it again now', 'rowcallRunAgain')
        .addItem('Get the last run\'s records', 'rowcallCollectLastRun')
        .addSeparator()
        .addItem('Refresh every day', 'rowcallRefreshDaily')
        .addItem('Stop the daily refresh', 'rowcallStopDaily')
        .addToUi();
    }
    
    /** Saves the API key in this script's user properties after checking it with GET /v1/me. */
    function rowcallSetKey() {
      var ui = SpreadsheetApp.getUi();
      var answer = ui.prompt(ROWCALL.name + ': API key',
        'Paste your API key. Create one in the console: ' + ROWCALL.baseUrl + '/console\n' +
        'It is kept in your user properties for this script, never in a cell.', ui.ButtonSet.OK_CANCEL);
      if (answer.getSelectedButton() !== ui.Button.OK) return;
      var key = cleanKey_(answer.getResponseText());
      if (!key) return say_('That does not look like an API key. Copy the whole key from the console and try again.');
      var me = fetchJson_(request_(ROWCALL.baseUrl, 'get', '/v1/me', key));
      if (!me.ok) return say_(me.message);
      PropertiesService.getUserProperties().setProperty(ROWCALL_KEY_PROP, key);
      var workspace = me.body.workspace || {};
      var meta = fetchJson_(request_(ROWCALL.baseUrl, 'get', '/v1/meta', null));
      var per1k = meta.ok ? Number(meta.body.default_units_per_1k) : 0;
      var covers = per1k > 0 && Number(workspace.units_balance) >= 0 ? Math.floor(workspace.units_balance * 1000 / per1k) : null;
      say_('Key saved' + (workspace.name ? ' for the workspace "' + workspace.name + '"' : '') + '.' +
        (covers === null ? '' : ' Your balance covers ' + formatCount_(covers) + ' records at the base price. Each API\'s page shows its own price.'));
    }
    
    /** Asks for an API, its inputs and a record limit, runs it and writes the records into the active sheet. */
    function rowcallRunIntoSheet() {
      var ui = SpreadsheetApp.getUi();
      var sheet = SpreadsheetApp.getActiveSheet();
      var key = keyOrSay_();
      if (!key) return;
    
      var apiAnswer = ui.prompt(ROWCALL.name + ': which API?',
        'Paste the API\'s slug, its id or the address of its page, for example python-job-board.\n' +
        'Browse them at ' + ROWCALL.baseUrl + '/catalog', ui.ButtonSet.OK_CANCEL);
      if (apiAnswer.getSelectedButton() !== ui.Button.OK) return;
      var api = parseApiRef_(apiAnswer.getResponseText());
      if (!api) return say_('Give the slug of an API, for example python-job-board. Its catalog page shows it: ' + ROWCALL.baseUrl + '/catalog');
    
      var inputAnswer = ui.prompt(ROWCALL.name + ': inputs (optional)',
        'The API\'s inputs as JSON, or leave empty to use its defaults. Its page lists them.\n' +
        'Example: {"keywords": "data analyst", "location": "Toronto, Ontario, Canada"}', ui.ButtonSet.OK_CANCEL);
      if (inputAnswer.getSelectedButton() !== ui.Button.OK) return;
      var input = parseInput_(inputAnswer.getResponseText());
      if (input.error) return say_(input.error);
    
      var limitAnswer = ui.prompt(ROWCALL.name + ': how many records?',
        'The most records to fetch. Leave empty for ' + ROWCALL.defaultMaxRecords + '; up to ' + formatCount_(ROWCALL.mostRecords) +
        '. You pay only for records returned.', ui.ButtonSet.OK_CANCEL);
      if (limitAnswer.getSelectedButton() !== ui.Button.OK) return;
      var maxItems = parseMaxRecords_(limitAnswer.getResponseText());
      if (maxItems.error) return say_(maxItems.error);
    
      var saved = loadSettings_(sheet.getSheetId());
      if (sheet.getLastRow() > 0 && !(saved && saved.lastRun && saved.lastRun.records > 0)) {
        var sure = ui.alert(ROWCALL.name, 'This replaces everything on the sheet "' + sheet.getName() + '". Continue?', ui.ButtonSet.YES_NO);
        if (sure !== ui.Button.YES) return;
      }
      runAndReport_(sheet, { api: api, input: input.value, maxItems: maxItems.value }, key);
    }
    
    /** Repeats this sheet's last run with the same API, inputs and limit. */
    function rowcallRunAgain() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var settings = loadSettings_(sheet.getSheetId());
      if (!settings || !settings.api) return say_('Nothing to repeat yet. Use Rowcall > Run an API into this sheet first.');
      var key = keyOrSay_();
      if (key) runAndReport_(sheet, settings, key);
    }
    
    /** Collects a run that was still going when the script had to stop following it. */
    function rowcallCollectLastRun() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var settings = loadSettings_(sheet.getSheetId());
      var runId = settings && settings.pendingRunId;
      if (!runId) return say_('This sheet has no run waiting to be collected.');
      var key = keyOrSay_();
      if (!key) return;
      var got = fetchJson_(request_(ROWCALL.baseUrl, 'get', '/v1/runs/' + encodeURIComponent(runId), key));
      if (!got.ok) return say_(got.message);
      SpreadsheetApp.getActive().toast('Reading the records of run ' + runId + '.', ROWCALL.name, -1);
      var outcome = withLock_(function () { return finishRun_(sheet, settings, key, got.body.run, null, null, Date.now() + ROWCALL.followMs); });
      saveOutcome_(sheet, settings, outcome);
      say_(outcome.message);
    }
    
    /** Installs one daily trigger that repeats this sheet's last run. */
    function rowcallRefreshDaily() {
      var ui = SpreadsheetApp.getUi();
      var ss = SpreadsheetApp.getActive();
      var sheet = ss.getActiveSheet();
      var settings = loadSettings_(sheet.getSheetId());
      if (!settings || !settings.api) return say_('Run an API into this sheet first (Rowcall > Run an API into this sheet). The daily refresh repeats that run.');
      if (!keyOrSay_()) return;
      var zone = ss.getSpreadsheetTimeZone();
      var answer = ui.prompt(ROWCALL.name + ': refresh every day',
        'At what hour? A whole number from 0 to 23, in the spreadsheet\'s time zone (' + zone + '). Leave empty for 6.', ui.ButtonSet.OK_CANCEL);
      if (answer.getSelectedButton() !== ui.Button.OK) return;
      var hour = parseHour_(answer.getResponseText());
      if (hour === null) return say_('The hour must be a whole number from 0 to 23.');
    
      removeDailyTriggers_(sheet.getSheetId());
      var trigger = ScriptApp.newTrigger('rowcallDailyRefresh').timeBased().everyDays(1).atHour(hour).inTimezone(zone).create();
      PropertiesService.getDocumentProperties().setProperty(triggerProp_(trigger.getUniqueId()), String(sheet.getSheetId()));
      settings.daily = { hour: hour, zone: zone };
      saveSettings_(sheet.getSheetId(), settings);
      say_('"' + sheet.getName() + '" will refresh every day between ' + hour + ':00 and ' + (hour + 1) + ':00 (' + zone + '; Google picks the minute), ' +
        'running ' + settings.api + ' for up to ' + formatCount_(settings.maxItems) + ' records. Each refresh replaces the sheet and is charged like any run. ' +
        'Rowcall > Stop the daily refresh turns it off.');
    }
    
    /** Removes this sheet's daily trigger. */
    function rowcallStopDaily() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var removed = removeDailyTriggers_(sheet.getSheetId());
      var settings = loadSettings_(sheet.getSheetId());
      if (settings && settings.daily) { delete settings.daily; saveSettings_(sheet.getSheetId(), settings); }
      say_(removed ? 'The daily refresh of "' + sheet.getName() + '" is off.' : 'This sheet has no daily refresh that you set up. A trigger made by another editor can only be removed by them.');
    }
    
    /** The daily trigger's handler. Failures keep the old records, say why in the note on A1, and reach you as Google's failure email. */
    function rowcallDailyRefresh(e) {
      var uid = e && e.triggerUid;
      var props = PropertiesService.getDocumentProperties();
      var sheetId = uid ? props.getProperty(triggerProp_(uid)) : null;
      var sheet = sheetId === null ? null : sheetById_(Number(sheetId));
      if (!sheet) {                                   // the sheet was deleted: remove its trigger
        if (uid) { deleteTriggerByUid_(uid); props.deleteProperty(triggerProp_(uid)); }
        return;
      }
      var settings = loadSettings_(sheet.getSheetId());
      var key = PropertiesService.getUserProperties().getProperty(ROWCALL_KEY_PROP);
      var outcome = !settings || !settings.api ? { ok: false, message: 'This sheet has no saved run to repeat.' }
        : !key ? { ok: false, message: 'No API key is saved. Use Rowcall > Set API key.' }
        : withLock_(function () { return runToSheet_(sheet, settings, key); });
      if (settings) saveOutcome_(sheet, settings, outcome);
      if (!outcome.ok) {
        noteOnSheet_(sheet, 'Daily refresh on ' + stamp_() + ' did not replace these records: ' + outcome.message);
        throw new Error(ROWCALL.name + ' daily refresh of "' + sheet.getName() + '": ' + outcome.message);
      }
    }
    
    // ─────────────────────────────────────────────────────────────── running
    
    function runAndReport_(sheet, settings, key) {
      SpreadsheetApp.getActive().toast('Running ' + settings.api + '. A large run can take a few minutes.', ROWCALL.name, -1);
      var outcome = withLock_(function () { return runToSheet_(sheet, settings, key); });
      saveOutcome_(sheet, settings, outcome);
      SpreadsheetApp.getActive().toast(outcome.ok ? 'Done.' : 'Stopped.', ROWCALL.name, 3);
      say_(outcome.message);
    }
    
    /** Starts a run, follows it, reads its records and writes them. Returns {ok, message, records?, run?, pending?}. */
    function runToSheet_(sheet, settings, key) {
      var deadline = Date.now() + ROWCALL.followMs;
      // One Idempotency-Key per run: a retry after a dropped connection gets the same run back and is never charged twice.
      var request = buildRunRequest_(ROWCALL.baseUrl, settings, key, 'sheets-' + Utilities.getUuid(), ROWCALL.waitSeconds);
      var res = fetchJson_(request, settings.api);
      if (!res.ok && res.status === 0) res = fetchJson_(request, settings.api);
      if (!res.ok) return { ok: false, message: res.message, code: res.code };
      var run = res.body.run;
      if (res.status === 200) return finishRun_(sheet, settings, key, run, res.body.records || [], res.body.next_cursor || null, deadline);
      return finishRun_(sheet, settings, key, run, null, null, deadline, retryAfter_(res.headers, 2));
    }
    
    /** Waits for the run to end (polling GET /v1/runs/:id), reads every record, then writes the sheet. */
    function finishRun_(sheet, settings, key, run, records, cursor, deadline, firstDelay) {
      var delay = Math.max(2, firstDelay || 2);
      while (ROWCALL_ACTIVE.indexOf(run.status) >= 0) {
        if (Date.now() + delay * 1000 > deadline) {
          return { ok: false, pending: true, run: run, message: 'The run is still going after ' + Math.round(ROWCALL.followMs / 60000 * 10) / 10 +
            ' minutes. Use Rowcall > Get the last run\'s records in a few minutes. Only the records it returns are charged.' };
        }
        Utilities.sleep(delay * 1000);
        var polled = fetchJson_(request_(ROWCALL.baseUrl, 'get', '/v1/runs/' + encodeURIComponent(run.id), key));
        if (polled.ok) run = polled.body.run;
        else if (polled.status !== 0 && polled.status < 500) return { ok: false, message: polled.message };
        delay = nextPollDelay_(delay);
      }
      if (run.status === 'failed' && !run.records_count) {
        return { ok: false, run: run, message: (run.error && run.error.message) || 'The run failed before any record arrived. Nothing was charged.' };
      }
      if (records === null) { records = []; cursor = ''; }
      while (cursor !== null && records.length < settings.maxItems) {
        if (Date.now() > deadline) return { ok: false, pending: true, run: run, message: 'Reading the records took too long. Use Rowcall > Get the last run\'s records to try again.' };
        var path = '/v1/runs/' + encodeURIComponent(run.id) + '/records?limit=' + ROWCALL.pageSize + (cursor ? '&cursor=' + encodeURIComponent(cursor) : '');
        var page = fetchJson_(request_(ROWCALL.baseUrl, 'get', path, key));
        if (!page.ok) return { ok: false, run: run, message: page.message };
        records = records.concat(page.body.records || []);
        cursor = page.body.next_cursor === undefined ? null : page.body.next_cursor;
      }
      records = records.slice(0, settings.maxItems);
      var notes = (run.summary && run.summary.notes) || [];
      if (!records.length) {
        return { ok: false, run: run, message: 'The run finished with no records, so the sheet was left as it was.' + (notes.length ? ' ' + notes.join(' ') : '') };
      }
      var table = recordsToTable_(records, ROWCALL);
      writeTable_(sheet, table);
      noteOnSheet_(sheet, ROWCALL.name + ' run ' + run.id + '\n' + stamp_() + '\n' + records.length + ' records from ' + settings.api +
        '\nStopped: ' + (run.stop_reason || 'done') + '\nUnits charged: ' + (run.units_charged || 0));
      return { ok: true, run: run, records: records.length,
        message: formatCount_(records.length) + ' records from ' + settings.api + ' written to "' + sheet.getName() + '".' +
          stopNote_(run.stop_reason, settings.maxItems) + (table.dropped ? ' ' + table.dropped + ' more fields were left out (the sheet keeps ' + ROWCALL.maxColumns + ').' : '') };
    }
    
    function stopNote_(reason, maxItems) {
      if (reason === 'max_items') return ' It stopped at your limit of ' + formatCount_(maxItems) + '.';
      if (reason === 'out_of_units') return ' Your balance ran out before the end: add records in the console to get the rest.';
      if (reason === 'timeout') return ' The run reached its time limit; these are the records read before it.';
      if (reason === 'blocked') return ' The site asked for a bot check partway, so the run stopped there.';
      return '';
    }
    
    // ─────────────────────────────────────────────────────────────── HTTP
    
    /** One request for UrlFetchApp: {url, params}. `key` may be null for public routes. */
    function request_(base, method, path, key, body, extraHeaders) {
      var headers = { Accept: 'application/json', 'ngrok-skip-browser-warning': '1' };   // the skip header lets non-browser clients through to the API
      if (key) headers.Authorization = 'Bearer ' + key;
      for (var name in (extraHeaders || {})) headers[name] = extraHeaders[name];
      var params = { method: method, headers: headers, muteHttpExceptions: true };
      if (body !== undefined) { params.contentType = 'application/json'; params.payload = JSON.stringify(body); }
      return { url: base + path, params: params };
    }
    
    /** POST /v1/apis/:id/run with the sheet's settings. */
    function buildRunRequest_(base, settings, key, idempotencyKey, waitSeconds) {
      var body = { max_items: settings.maxItems, wait_seconds: waitSeconds };
      if (settings.input && Object.keys(settings.input).length) body.input = settings.input;
      return request_(base, 'post', '/v1/apis/' + encodeURIComponent(settings.api) + '/run', key, body, { 'Idempotency-Key': idempotencyKey });
    }
    
    /** Sends a request and reads the JSON answer. Never throws: {ok, status, body, headers, code?, message?}. */
    function fetchJson_(request, apiRef) {
      var response;
      try {
        response = UrlFetchApp.fetch(request.url, request.params);
      } catch (err) {
        return { ok: false, status: 0, code: 'network_error', message: 'Could not reach ' + ROWCALL.name + '. Check your connection and try again.' };
      }
      var status = response.getResponseCode();
      var headers = response.getHeaders() || {};
      var body = null;
      try { body = JSON.parse(response.getContentText()); } catch (err) { body = null; }
      if (body === null || typeof body !== 'object') {
        return { ok: false, status: status, headers: headers, code: 'not_json', message: 'The server did not answer with data (HTTP ' + status + '). Try again in a minute.' };
      }
      if (status >= 200 && status < 300) return { ok: true, status: status, body: body, headers: headers };
      var error = body.error || {};
      return { ok: false, status: status, body: body, headers: headers, code: error.code || '', message: describeError_(status, error, apiRef, retryAfter_(headers, 0)) };
    }
    
    /** What went wrong, then what to do next. */
    function describeError_(status, error, apiRef, retryAfterSeconds) {
      var code = (error && error.code) || '';
      var said = (error && error.message) || '';
      var ref = error && error.request_id ? ' (request id ' + error.request_id + ')' : '';
      if (status === 401) return 'This API key is not valid. Create a new one in the console (' + ROWCALL.baseUrl + '/console), then use Rowcall > Set API key.';
      if (status === 402 || code === 'out_of_units') return 'Your balance cannot cover one more record. Add records in the console (' + ROWCALL.baseUrl + '/console) to keep going.';
      if (code === 'backend_unavailable') {
        return 'Live runs for this API open soon. Its page shows sample records' + (apiRef ? ': ' + ROWCALL.baseUrl + '/catalog/' + encodeURIComponent(apiRef) : '') + '. Pick another API for now.';
      }
      if (code === 'api_not_found') return 'No API called "' + (apiRef || '') + '". Copy the slug from its catalog page: ' + ROWCALL.baseUrl + '/catalog';
      if (status === 429) return 'Too many requests right now. Try again in ' + Math.max(1, retryAfterSeconds || Number(error && error.retry_after_seconds) || 60) + ' seconds.';
      if (said) return said + ref;
      if (status >= 500) return 'Something went wrong on our side. Try again in a minute.' + ref;
      return 'The request was refused (HTTP ' + status + ').' + ref;
    }
    
    function header_(headers, name) {
      var wanted = String(name).toLowerCase();
      for (var key in (headers || {})) if (key.toLowerCase() === wanted) return headers[key];
      return null;
    }
    
    function retryAfter_(headers, fallback) {
      var seconds = Number(header_(headers, 'retry-after'));
      return isFinite(seconds) && seconds > 0 ? Math.min(seconds, 60) : fallback;
    }
    
    /** Polls start at the server's Retry-After and slow down to every 10 seconds. */
    function nextPollDelay_(seconds) {
      return Math.min(10, Math.ceil(seconds * 1.5));
    }
    
    // ─────────────────────────────────────────────────────────────── records to cells
    
    /** One record as a flat {column: value} object. Objects become dotted columns; lists become one cell. */
    function flattenRecord_(record, maxDepth) {
      var out = {};
      if (record === null || typeof record !== 'object' || Array.isArray(record)) { out.value = Array.isArray(record) ? listCell_(record) : record; return out; }
      (function walk(value, prefix, depth) {
        if (value === null || value === undefined) { out[prefix] = ''; return; }
        if (Array.isArray(value)) { out[prefix] = listCell_(value); return; }
        if (typeof value === 'object') {
          var keys = Object.keys(value);
          if (depth > 0 && !keys.length) { out[prefix] = ''; return; }
          if (depth >= maxDepth) { out[prefix] = JSON.stringify(value); return; }
          for (var i = 0; i < keys.length; i += 1) walk(value[keys[i]], prefix ? prefix + '.' + keys[i] : keys[i], depth + 1);
          return;
        }
        out[prefix] = value;
      })(record, '', 0);
      return out;
    }
    
    /** A list of plain values is joined with commas; a list holding objects is kept as JSON text. */
    function listCell_(list) {
      if (!list.length) return '';
      var plain = list.every(function (item) { return item === null || ['string', 'number', 'boolean'].indexOf(typeof item) >= 0; });
      if (!plain) return JSON.stringify(list);
      return list.filter(function (item) { return item !== null && item !== ''; }).join(', ');
    }
    
    /** Every column name in the order first seen, up to `maxColumns`. */
    function buildHeader_(flatRecords, maxColumns) {
      var seen = {};
      var header = [];
      var dropped = 0;
      flatRecords.forEach(function (flat) {
        Object.keys(flat).forEach(function (name) {
          if (seen[name]) return;
          seen[name] = true;
          if (header.length < maxColumns) header.push(name);
          else dropped += 1;
        });
      });
      return { header: header, dropped: dropped };
    }
    
    /**
     * The value a cell gets. Numbers and true/false stay typed. Text is written with a leading apostrophe, so Sheets keeps
     * it exactly as sent: no formulas from a web page, no lost leading zeros, no dates guessed from text.
     */
    function cellValue_(value, maxChars) {
      if (value === null || value === undefined || value === '') return '';
      if (typeof value === 'number') return isFinite(value) ? value : '';
      if (typeof value === 'boolean') return value;
      var text = typeof value === 'string' ? value : JSON.stringify(value);
      var most = maxChars || ROWCALL.maxCellChars;
      if (text.length > most) text = text.slice(0, most - 1) + '…';
      return '\'' + text;
    }
    
    /** Records to {header, rows, dropped}: header holds the column names, rows the cell values. */
    function recordsToTable_(records, options) {
      var flat = records.map(function (record) { return flattenRecord_(record, options.maxDepth); });
      var built = buildHeader_(flat, options.maxColumns);
      var rows = flat.map(function (one) {
        return built.header.map(function (name) { return cellValue_(one[name], options.maxCellChars); });
      });
      return { header: built.header, rows: rows, dropped: built.dropped };
    }
    
    function writeTable_(sheet, table) {
      var values = [table.header.map(function (name) { return cellValue_(name); })].concat(table.rows);
      var width = Math.max(1, table.header.length);
      if (sheet.getMaxRows() < values.length) sheet.insertRowsAfter(sheet.getMaxRows(), values.length - sheet.getMaxRows());
      if (sheet.getMaxColumns() < width) sheet.insertColumnsAfter(sheet.getMaxColumns(), width - sheet.getMaxColumns());
      sheet.clearContents();
      sheet.getRange(1, 1, values.length, width).setValues(values);
      sheet.getRange(1, 1, 1, width).setFontWeight('bold');
      sheet.setFrozenRows(1);
    }
    
    // ─────────────────────────────────────────────────────────────── inputs from the prompts
    
    /** A slug, an id, or the address of its catalog or API page. Returns '' when nothing usable was given. */
    function parseApiRef_(text) {
      var value = String(text || '').trim();
      var match = value.match(/\/(?:catalog|apis)\/([^\/?#\s]+)/);
      if (match) value = match[1];
      value = value.replace(/\.md$/, '');
      try { value = decodeURIComponent(value); } catch (err) { /* keep as typed */ }
      return /^[A-Za-z0-9][A-Za-z0-9_.~-]{0,199}$/.test(value) ? value : '';
    }
    
    /** Optional JSON object for `input`. Returns {value} or {error}. */
    function parseInput_(text) {
      var value = String(text || '').trim();
      if (!value) return { value: {} };
      var parsed;
      try { parsed = JSON.parse(value); } catch (err) {
        return { error: 'The inputs are not valid JSON. Use double quotes, for example {"keywords": "data analyst"}.' };
      }
      if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return { error: 'The inputs must be one JSON object, for example {"keywords": "data analyst"}.' };
      return { value: parsed };
    }
    
    /** Record limit from the prompt. Returns {value} or {error}. */
    function parseMaxRecords_(text) {
      var value = String(text || '').replace(/[,\s]/g, '');
      if (!value) return { value: ROWCALL.defaultMaxRecords };
      if (!/^\d+$/.test(value) || Number(value) < 1) return { error: 'The number of records must be a whole number of 1 or more.' };
      return { value: Math.min(Number(value), ROWCALL.mostRecords) };
    }
    
    function parseHour_(text) {
      var value = String(text || '').trim();
      if (!value) return 6;
      return /^\d{1,2}$/.test(value) && Number(value) <= 23 ? Number(value) : null;
    }
    
    function cleanKey_(text) {
      var key = String(text || '').trim().replace(/^Bearer\s+/i, '');
      return /^[A-Za-z0-9_\-.~+\/=]{16,300}$/.test(key) ? key : '';
    }
    
    // ─────────────────────────────────────────────────────────────── saved settings and triggers
    
    function settingsProp_(sheetId) { return 'rowcall.sheet.' + sheetId; }
    function triggerProp_(uid) { return 'rowcall.trigger.' + uid; }
    
    /** A sheet's last run settings ({api, input, maxItems, lastRun, pendingRunId, daily}) live in document properties. */
    function loadSettings_(sheetId) {
      var text = PropertiesService.getDocumentProperties().getProperty(settingsProp_(sheetId));
      if (!text) return null;
      try { return JSON.parse(text); } catch (err) { return null; }
    }
    
    function saveSettings_(sheetId, settings) {
      PropertiesService.getDocumentProperties().setProperty(settingsProp_(sheetId), JSON.stringify(settings));
    }
    
    /** Remembers what a run did. Settings are kept only once a run worked, so a mistyped input is never scheduled. */
    function saveOutcome_(sheet, settings, outcome) {
      var next = loadSettings_(sheet.getSheetId()) || {};
      if (outcome.ok) {
        next.api = settings.api; next.input = settings.input || {}; next.maxItems = settings.maxItems;
        next.lastRun = { id: outcome.run.id, at: new Date().toISOString(), records: outcome.records };
        delete next.pendingRunId;
      } else if (outcome.pending && outcome.run) {
        next.api = settings.api; next.input = settings.input || {}; next.maxItems = settings.maxItems;
        next.pendingRunId = outcome.run.id;
      } else if (!next.api) {
        return;
      }
      saveSettings_(sheet.getSheetId(), next);
    }
    
    /** Deletes your daily triggers for one sheet and forgets them. Returns how many were removed. */
    function removeDailyTriggers_(sheetId) {
      var props = PropertiesService.getDocumentProperties();
      var removed = 0;
      ScriptApp.getProjectTriggers().forEach(function (trigger) {
        var uid = trigger.getUniqueId();
        if (trigger.getHandlerFunction() === 'rowcallDailyRefresh' && props.getProperty(triggerProp_(uid)) === String(sheetId)) {
          ScriptApp.deleteTrigger(trigger);
          props.deleteProperty(triggerProp_(uid));
          removed += 1;
        }
      });
      return removed;
    }
    
    function deleteTriggerByUid_(uid) {
      ScriptApp.getProjectTriggers().forEach(function (trigger) { if (trigger.getUniqueId() === uid) ScriptApp.deleteTrigger(trigger); });
    }
    
    // ─────────────────────────────────────────────────────────────── small helpers
    
    function keyOrSay_() {
      var key = PropertiesService.getUserProperties().getProperty(ROWCALL_KEY_PROP);
      if (!key) say_('Set your API key first: Rowcall > Set API key. Create a key in the console: ' + ROWCALL.baseUrl + '/console');
      return key;
    }
    
    /** One run writes to a spreadsheet at a time. */
    function withLock_(work) {
      var lock = LockService.getDocumentLock();
      if (!lock.tryLock(10000)) return { ok: false, message: 'Another ' + ROWCALL.name + ' run is writing to this spreadsheet. Try again when it is done.' };
      try { return work(); } finally { lock.releaseLock(); }
    }
    
    function sheetById_(sheetId) {
      var sheets = SpreadsheetApp.getActive().getSheets();
      for (var i = 0; i < sheets.length; i += 1) if (sheets[i].getSheetId() === sheetId) return sheets[i];
      return null;
    }
    
    function noteOnSheet_(sheet, text) {
      sheet.getRange(1, 1).setNote(text);
    }
    
    function say_(message) {
      SpreadsheetApp.getUi().alert(ROWCALL.name, message, SpreadsheetApp.getUi().ButtonSet.OK);
    }
    
    function stamp_() {
      var ss = SpreadsheetApp.getActive();
      return Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone(), 'MMM d, yyyy HH:mm');
    }
    
    function formatCount_(n) {
      return String(Math.round(Number(n) || 0)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
    
  2. Paste your key

    Choose Set API key in the new menu and paste a key from the console. The script checks it before saving it.

    The first time, Google asks you to allow the script: to see and change this spreadsheet only, to connect to an outside service, and to run while you are away. Because you added the script yourself, Google says it has not verified the app; choose Advanced, then go to your project. Some work accounts do not allow scripts that Google has not verified.

  3. Pick an API

    Find one in the catalog and copy its slug, the last part of its address: /catalog/python-job-board gives python-job-board. You can also paste the whole address.

    Its page lists its inputs. They go in as one JSON object, for example {"keywords": "data analyst", "location": "Toronto, Ontario, Canada"} for linkedin-jobs. Leave them empty to use the API's defaults.

  4. Run it

    Choose Run an API into this sheet, give the slug, the inputs and the most records to fetch (100 when left empty). The records replace what is on the sheet, and a note on cell A1 says which run it was, when, and how many records it returned.

  5. Schedule it

    Choose Refresh every day and pick an hour. Google runs it at a minute of its choosing within that hour, with the same API, inputs and limit. Stop the daily refresh turns it off.

    If a refresh cannot finish, the old records stay on the sheet, the note on A1 says why, and Google emails you about the failed run.

What the sheet looks like

RowABCDEFG
1urltitlecompanylocationposted_attagsremote
2https://www.python.org/jobs/8228/Software Developer Intern (Python / Full-Stack)Nestack Technologies Pvt LtdHyderabad, Telangana, India2026-11-23T14:04:36ZBack end, Front end, Web
3https://www.python.org/jobs/8213/Internet Measurement Researcher (Censorship & Proxies)TGScopeRemote, North America, Europe2026-11-15T17:13:09ZBack end, Database, Systems, TestingTRUE
4https://www.python.org/jobs/8212/Research Scientist, Coordinated Networks & Information IntegrityTGScopeRemote, North America, Europe2026-11-15T17:11:42ZBig Data, Database, Machine LearningTRUE
Example Three saved sample records of python-job-board (Nov 2026), as the script writes them. The header comes from the fields. The tags list shares one cell. remote is empty where a posting does not say.

Limits and pricing

  • The script is free. Runs from a sheet cost the same as any other run: each API's page shows its price per 1,000 records. Zero records cost zero.
  • Each run, and each daily refresh, replaces everything on its sheet. Keep your own formulas and notes on another sheet.
  • Up to 10,000 records per run. That is the script's own limit, so a run and the writing fit inside Google's 6-minute limit for a script.
  • The script follows a run for about 4.5 minutes. A longer run keeps going on our side; Get the last run's records collects it later.
  • Up to 300 columns. A cell holds up to 50,000 characters, so longer text is cut.
  • Numbers and true or false stay typed. Text is written exactly as the API sent it, so a value from a web page never becomes a formula. Dates stay as ISO 8601 text: they sort correctly and do not shift with time zones.
  • A ready-made API whose page says "Live runs for this API open soon" cannot run yet. The script says so and leaves the sheet as it was.
  • The daily refresh runs as the Google account that set it up, with that account's key. Google's own daily quotas for scripts apply.