OĞUZ EROLAI·ADS·APPS

Google Sheets Import JSON from an API: Apps Script, Paging and Upsert

13 min readPublished: Updated:
CONTENTS9 sections

Google Sheets has no built-in formula for importing JSON from an API; this guide’s route is Apps Script. No web function in Google’s list reads JSON; IMPORTDATA takes only CSV and TSV. You request with UrlFetchApp, decode with JSON.parse, flatten nested fields and write rows. The real work is next: keeping the key out of the code, reading every page, retrying temporary errors, never writing a record twice. Over 20 fictional mornings, a script appending every fetch produced 2,492 duplicate rows and showed ordered quantity at 1.74 times reality; updating rows by key (upsert) left a table that matched the ERP (the scenario deletes nothing).

For finance, purchasing and operations teams. Web page tables are covered in importing website data into Google Sheets.

Does Google Sheets have a built-in JSON import function?

None of the IMPORT functions in the web category (IMPORTDATA, IMPORTFEED, IMPORTHTML, IMPORTRANGE, IMPORTXML) reads JSON (Google function list, 2026-10-31). Google describes IMPORTDATA as importing CSV or TSV data from a URL (IMPORTDATA). If your API also serves CSV, that may be shortest, but Google lists the URL as its only parameter, with no request headers. A key in the URL sits in the formula; assume anyone who can open the file sees it in the formula bar.

Community custom functions also fetch JSON. Google says (2026-10-31) one must return within 30 seconds, writes only to its own cell and recalculates only when arguments change (custom functions). Fine for one rate; a paginated order list suits a scheduled script.

Example: an ERP order API over 20 consecutive mornings

This example is fictional; the figures come from a scenario script. A spare-parts manufacturer’s planning team copies open orders and due dates from the ERP every morning. Its order API returns JSON, 50 orders per page, with a “changed after” filter. A shortened record:

{"orderNo": 10231, "status": "in_production", "updatedAt": "...",
 "customer": {"code": "C-118", "name": "...", "contact": {"name": "...", "phone": "..."}},
 "tags": ["export", "urgent"],
 "lines": [{"lineNo": 1, "partCode": "YP-0412", "qty": 12, "dueDate": "..."}],
 "shipments": [{"no": "S-77", "date": "...", "carrier": "...", "trackingNo": "..."}]}

The script runs at 07:00: the whole list first, then changes since the last successful run. Twenty mornings in summary:

result
first run486 orders, 10 pages, 1,630 order lines
morning runs20: run 9 stopped at the count check and was rerun, run 15 failed
API calls53, five returned an error code
rows received, all runs5,866: 3,381 new, 1,133 updated, 1,352 unchanged
after morning 20970 orders, 3,381 lines, matching the ERP
if every run appended5,873 rows (2,492 duplicates); without a count check, 7 more than 5,866 on run 9
if every run cleared and rewroteonly the last run’s 211 rows

Fetching with Apps Script: a skeleton

One question first: can the internet reach your ERP? Requests leave from Google’s servers, from a set pool of IP ranges whose list Google publishes (UrlFetchApp); its help page says the ranges change often (Google IP ranges, 2026-10-31), so allowlisting may be impractical. An ERP only on the company network or behind a VPN is out of direct reach; you need an internet-reachable HTTPS endpoint (my inference). Ask IT first.

Before you start:

  1. Create two tabs, Order_Lines and Fetch_Log. Row 1 is the header: give Order_Lines the 19 column names in flatten order.
  2. Open Extensions > Apps Script and paste the code; under Project Settings > Script Properties, add the key as ERP_API_KEY.
  3. Adapt the address and field names to your API documentation.
const PAGE_SIZE = 50, OVERLAP_MS = 2 * 3600 * 1000, COLS = 19;

function fetchOrders() {
  const props = PropertiesService.getScriptProperties();
  const started = new Date();
  try {
    const last = props.getProperty('LAST_SUCCESS');
    const since = last ? new Date(new Date(last) - OVERLAP_MS).toISOString() : '';
    let orders = [], total = 0, page = 1, calls = 0;
    do {
      const url = 'https://erp.example.com/api/orders?pageSize=' + PAGE_SIZE +
        '&page=' + page + (since ? '&updatedAfter=' + encodeURIComponent(since) : '');
      const res = request(url, props.getProperty('ERP_API_KEY'));
      calls += res.calls;
      const data = JSON.parse(res.text);
      total = data.total;
      if (!data.items.length) break;
      orders = orders.concat(data.items);
      page++;
    } while (orders.length < total);
    const unique = new Set(orders.map(o => o.orderNo)).size;
    if (unique !== total) throw new Error('Count mismatch: API ' + total + ', unique ' + unique);
    const rows = [];
    orders.forEach(o => o.lines.forEach(l => rows.push(flatten(o, l, started))));
    const result = upsert(rows);
    props.setProperty('LAST_SUCCESS', started.toISOString());
    logRun([started, 'ok', total, rows.length, result.added,
      result.updated, result.skipped, calls, '']);
  } catch (e) {
    logRun([started, 'error', '', '', '', '', '', '', e.message]);
    throw e;  // keep Google's failure email
  }
}

function request(url, key) {
  for (let attempt = 1; attempt <= 4; attempt++) {
    const res = UrlFetchApp.fetch(url, {
      headers: {Authorization: 'Bearer ' + key}, muteHttpExceptions: true});
    const code = res.getResponseCode();
    if (code === 200) return {text: res.getContentText(), calls: attempt};
    if (code !== 429 && code < 500) throw new Error('HTTP ' + code + ', not retried');
    const h = res.getHeaders();
    const wait = Number(h['Retry-After'] || h['retry-after']) || Math.pow(2, attempt);
    if (attempt < 4) Utilities.sleep(Math.min(wait, 60) * 1000);
  }
  throw new Error('Failed after four attempts: ' + url);
}

function flatten(o, l, time) {
  const ship = o.shipments || [];
  return [o.orderNo + '-' + l.lineNo, o.orderNo, o.status, o.createdAt, o.updatedAt,
    o.customer.code, o.customer.name, o.currency, (o.tags || []).join(', '),
    l.lineNo, l.partCode, l.description, l.qty, l.unit, l.unitPrice, l.dueDate,
    ship.length, ship.map(x => x.date).sort().pop() || '', time].map(v => v ?? '');
}

function upsert(incoming) {
  const sh = SpreadsheetApp.getActive().getSheetByName('Order_Lines');
  sh.getRangeList(['A:A', 'D:F', 'K:K', 'P:P', 'R:R']).setNumberFormat('@');
  const n = sh.getLastRow() - 1;
  const table = n > 0 ? sh.getRange(2, 1, n, COLS).getValues() : [];
  const pos = new Map(table.map((r, i) => [String(r[0]), i]));
  const count = {added: 0, updated: 0, skipped: 0};
  const same = (a, b) => JSON.stringify(a.slice(0, 18)) === JSON.stringify(b.slice(0, 18));
  incoming.forEach(r => {
    const i = pos.get(r[0]);
    if (i === undefined) { pos.set(r[0], table.length); table.push(r); count.added++; }
    else if (same(table[i], r)) count.skipped++;
    else { table[i] = r; count.updated++; }
  });
  if (table.length) sh.getRange(2, 1, table.length, COLS).setValues(table);
  return count;
}

function logRun(row) {
  SpreadsheetApp.getActive().getSheetByName('Fetch_Log').appendRow(row);
}

Read the authorisation screen on the first run. Without muteHttpExceptions, fetch throws on an error code instead of returning the response (UrlFetchApp), so the script reads the status code itself. A time-driven trigger runs it daily; its time window and failure emails are in Google Sheets threshold alerts.

Keep the key out of the code

Step 2’s Script Properties exist for this; the script reads the key with PropertiesService.getScriptProperties(). Google says (2026-10-31) script properties are shared by all users of a script, and up to 50 can be added by hand (Properties). Paste the code into a forum and the key stays behind; who can still read it is in the FAQ. Ask for a read-only key where possible.

Pagination and the count check

A paginated fetch is incomplete until every page is read, with no error raised. The skeleton reads pages up to total, stopping on an empty page.

On run 9 the API reported 66 orders and two pages brought 66 records, yet only 65 were unique. After page one, an order on page two was updated and jumped to the top; everything shifted by one, page one’s last order reappeared and the updated order never arrived. “Received equals total” misses this; a unique-key count catches it. The script stopped before writing; a manual rerun straight away brought 66 unique orders. This explains the summary’s 7 extra rows: the appending script wrote the repeated 8-line order twice and the missed 1-line order only next morning. Page-number (offset) pagination carries this risk. Prefer a continuation cursor (next-page token) or oldest-first sorting if offered.

Error codes and retries

Error codes fall into two groups. 429 (“too many requests”) and 5xx are temporary: wait and retry. 401, 403 and 404 are permanent; retrying burns quota. The skeleton makes at most four attempts, waiting between them for Retry-After if sent, otherwise 2, 4 and 8 seconds; after the fourth it fails without waiting.

Five of 53 calls returned an error:

runcodewhat happened
6 and 19429server asked for 30 seconds, second attempt succeeded
11503waits of 2 and 4 seconds, third attempt succeeded
15401key had expired, no retry, run failed

On run 15, LAST_SUCCESS did not move; after renewal, run 16 started from run 14 and collected 116 orders on three pages.

Quotas and time limits

Per Google’s quota page (2026-10-31): URL Fetch 20,000 calls a day on consumer accounts, 100,000 on Workspace; 6 minutes per execution; total trigger runtime 90 minutes a day (consumer) or 6 hours (Workspace) (Apps Script quotas). Quotas can change without notice. The busiest morning used 10 calls. Time is tighter: Utilities.sleep pauses at most 5 minutes (Utilities), and waiting eats into the 6 minutes (my inference). Hence the 60-second cap. Large first loads need several runs.

How do you flatten nested JSON into a table?

First decide what a row represents. Planning works by part and due date, so one row is one order line, repeating order and customer fields. The record has 21 leaf fields (lowest value-holding fields):

  • Direct columns, 15 fields: order number, status, created, updated, currency, customer code, customer name, tags, and the line’s seven fields (line number, part code, description, quantity, unit, unit price, due date).
  • Array as text: tags joined with commas in one cell; for tag reports, one row per tag in a separate tab.
  • Array as summary: shipments become two columns, count and last shipment date. Number, carrier and tracking go to a Shipments tab linked by order number.
  • Left out, 2 fields: the customer contact’s name and phone. Planning does not need them, and keeping personal data out of a shared sheet beats controlling who sees it later.
  • Technical, 2 columns: the key (order number + line number) and the fetch time.

19 columns. Rule: open at most one array per row, or lines multiply with shipments. Customer names and prices you take land in a Google account: check your IT and data protection policy (not legal advice).

upsert sets the date, key, customer-code and part-code columns to plain text. Sheets may convert a written value to a date or number; if the type read back differs, unchanged rows count as “updated”. flatten turns empty or missing fields into empty text for the same reason. To filter by date, convert the text in a separate report tab, for example =DATEVALUE(LEFT(P2,10)) (untested); the source tab stays text.

Overwrite, append or upsert?

If the source returns the full list every time (all of today’s exchange rates, say), clearing and rewriting is correct. If it returns only changes, it is wrong: here only the last run’s 211 of 3,381 lines would remain.

Appending loses nothing but adds records again: an updated order returns with all its lines, and the two-hour overlap repeats part of the previous morning. The appending script reached 5,873 rows, 2,492 of them stale copies; a SUMIF on open quantity by part would show 1.74 times the real figure.

Upsert checks each key: absent, added; changed, overwritten; identical, left alone. Of 5,866 incoming rows, 3,381 were new, 1,133 updated and 1,352 unchanged, 235 of those only from the overlap window. Build the key from the API’s permanent identifiers (order number + line number), never from row position or customer name. If several sources share a tab, prefix the key with the source name. Upsert never removes records deleted in the ERP or no longer returned; unless cancellations come back as a status, compare against a full fetch now and then.

One more pattern for history: keep the current table with upsert and append a nightly summary row (open orders, total quantity) to a separate tab.

Last successful fetch and row counts

Fetch_Log gets a row per run (time, status, API total, received, added, updated, unchanged, calls, error) and answers two questions:

  • How fresh is the data? The last “ok” row’s time. Turn it red with conditional formatting after 26 hours. On run 15’s morning only this cell showed the data was a day old.
  • Is the volume normal? Single-day fetches ranged from 49 to 75 orders (excluding the first day and run 16, which covered two days). If a day brings 5, no error appears; the count column shows it.

Which route when?

routewhenlimit
IMPORTDATAAPI serves the same data as CSV/TSV, no key neededno JSON, no request headers
custom functionsingle value, such as the day’s rate30 seconds, own cell only
Apps Script with a triggerone source, paginated list, upsert6 min per run, runs as the installer
web applicationseveral sources, roles, approval, historywritten scope, server and maintenance

Where does a script stop being enough? Four questions

The limit is the work, not the technology: several people touching data with different permissions. Answer yes or no. The first happened in the example; the others may arise.

  1. Must two people see a stopped fetch the same morning? Google sends a failure summary email for triggers without naming the recipient; I assume it goes to whoever installed the trigger. Had that person been away on run 15, planning would have used stale data. Cheap fix: in catch, notify a shared team address with MailApp.sendEmail, plus the red freshness cell. Who took ownership or renewed the key is still not recorded.
  2. Will a second source (carrier, rates) link to the same orders? A separate script and tab per source is cheap. Matching records across sources and tracking errors in one place makes one script grow fast.
  3. Must some people not see a column? Cheap fix: a separate file for the workshop with only part, quantity and due date, shared separately. Protected ranges are no substitute: Google says they restrict editing, should not be used as a security measure, and viewers can access hidden sheets (protected ranges, 2026-10-31). More roles mean more files.
  4. Must a change from the ERP wait for approval? A due date, say, should not change the plan until the sales manager approves. A script writes or does not; “awaiting approval” has no cheap equivalent.

No to all: a triggered script is enough, and I would not recommend an application. Yes only to 1 and/or 3: try the cheap fix first. Yes to 2 or 4: write down the scope instead of patching the script; that is my threshold. On the application route the server (VPS) can be opened in your company’s name, you take the data as Excel or CSV any time, a small or mid-sized team pays no per-user licences, only server and maintenance, and the source code sits in a repository you can access with run instructions, dependency list and known limitations. An example with fetch log and missing-day rules is the scheduled API data import app.

I know API work first-hand: I pull Google Ads reports with my own Python script via the Google Ads API. For the scope, send your API documentation and today’s export, customer names masked, via the contact page; the first consultation is paid.

What I could not verify

Sources read 2026-10-31. Figures come from an asserted Python simulation of the skeleton (senaryo.py). Still open:

  • The skeleton has not been run against a real API or a real spreadsheet.
  • The letter case of header names returned by getHeaders(). The code tries both spellings.
  • How long upsert takes with 19 columns and a few thousand rows. I did not measure it.
  • The scenario never deletes a record.
  • Whether fetch throws on network errors (DNS, timeouts); the skeleton does not retry them.
  • That viewers can see the URL in an IMPORTDATA formula; assumed, not read from Google.

Frequently Asked Questions

If I share the spreadsheet, are the script and API key shared too?

A bound script lives with the file. Google does not say who can see script properties; assume anyone with edit access can read the key in project settings. Keep edit access narrow; give others view access, or copy results to a separate file.

What changes if the API requires OAuth instead of a key?

You must obtain, store and refresh an access token. Google Workspace’s OAuth2 library for Apps Script on GitHub creates tokens, refreshes them on expiry and suggests persisting them in a properties store; I have not tried it. It also raises whose account owns the token, and what happens when that person leaves.

What if the API expects POST with a query in the body instead of GET?

Pass method: 'post', contentType: 'application/json' and payload: JSON.stringify(query) in the second argument of UrlFetchApp.fetch. Google says contentType defaults to application/x-www-form-urlencoded, so a first attempt against a JSON API may return an error.

Back to top ↑