How to Fetch Paginated API Data in Google Apps Script

by Fahim Mahmud Chisti

To fetch paginated API data in Google Apps Script, you loop over the pages in memory, write the results to the sheet in one batch, and save your position so a new run can resume before the 6-minute limit stops the script. This tutorial gives you working loops for cursor and offset APIs, a resume pattern, batched writes and a retry helper for rate limits.

Quick answer: Request one page at a time with UrlFetchApp.fetch(), collect the records in an array, and write them with a single setValues() call. For large datasets, stop at about 5 minutes, store the cursor in PropertiesService, and let a one-off trigger continue the job.

  1. Store the API key as a script property and set the URL, page size and tab name at the top of the script.
  2. Use a cursor loop (next-page token) or an offset loop (skip and limit), depending on your API.
  3. Keep all records in memory and write them in one batch with setValues().
  4. Save the cursor and schedule a resume trigger before the 6-minute limit.
  5. Wrap requests in a retry helper that backs off on HTTP 429.
In this guide
  1. Before You Start
  2. Why Simple Loops Fail in Apps Script
  3. Step 1: Set Up the Script and Config
  4. Step 2: Handle Cursor-Based Pagination
  5. Step 3: Handle Offset-and-Limit Pagination
  6. Step 4: Resume Before the 6-Minute Limit
  7. Step 5: Write to the Sheet in One Batch
  8. Step 6: Retry When the API Rate-Limits You
  9. If It Still Doesn’t Work
  10. Frequently Asked Questions
  11. Next Steps
Close-up of Google Apps Script code handling cursor pagination in a dark-themed editor

Before You Start

  • API access: an API key or token, and the API’s documentation page on pagination. You need the names of its page-size, cursor or offset parameters and of the fields in its response.
  • A Google Sheet with a tab named API Data. The overwrite step clears that tab, so do not point it at a tab that holds other data.
  • Apps Script editor: open it from the sheet with Extensions > Apps Script. Paste every code block in this tutorial into the same Code.gs file.
  • Time: about 30 minutes to adapt the code to your API.

Why Simple Loops Fail in Apps Script

A basic Google Apps Script automation fetches an endpoint, parses the JSON and writes it to a sheet. That works until the dataset grows. Most APIs return only 50, 100 or 250 records per request, so you have to paginate: request page after page until there are no more.

A plain loop that fetches pages one by one runs into three Apps Script bottlenecks:

  • The 6-minute execution limit: Apps Script stops any script that runs longer than 6 minutes, on consumer and Google Workspace accounts alike. A slow API can easily eat through that.
  • Sheet write performance: If you append rows to a Google Sheet inside your loop, each call goes to the spreadsheet service and slows the script to a crawl.
  • API rate limits: Fire off hundreds of rapid requests, and the target API will quickly shut you down with 429 Too Many Requests errors.

The fix is to collect pages in memory, batch your sheet writes, and pause and resume before you reach the 6-minute limit.

Step 1: Set Up the Script and Config

Open a fresh Google Sheet, go to Extensions > Apps Script, and clear out the placeholder code. Save your API key under Project Settings > Script Properties as API_KEY instead of pasting it into the code, where anyone who can open the script could read it.

Then paste these settings at the very top of Code.gs, so you can change them in one place. Replace BASE_URL with your API’s endpoint:

const API_KEY = PropertiesService.getScriptProperties().getProperty('API_KEY');
const BASE_URL = 'https://api.example.com/v1/customers';
const LIMIT = 100; // Records per page
const SHEET_NAME = 'API Data'; // Tab the results are written to

All requests use the built-in UrlFetchApp service. The next two steps cover the two patterns you will meet most: cursor-based and offset-based pagination.

Step 2: Handle Cursor-Based Pagination

Cursor-based pagination is common on modern APIs such as Stripe, Slack or GoHighLevel. Instead of asking for page 5, you get a cursor token (like starting_after or next_page_token) with each response. You pass that token back in the next request to get the next batch.

The function below uses a do...while loop, so the first request always runs and the loop continues only while the API returns a next-page token. Paste it under the config:

function fetchAllCursorData() {
  let allRecords = [];
  let nextPageToken = null;
  let hasMore = true;
  let pageCounter = 1;
  do {
    // Build URL with cursor token if it exists
    let url = BASE_URL + '?limit=' + LIMIT;
    if (nextPageToken) {
      url += '&starting_after=' + encodeURIComponent(nextPageToken);
    }
    const options = {
      method: 'get',
      headers: {
        'Authorization': 'Bearer ' + API_KEY,
        'Accept': 'application/json'
      },
      muteHttpExceptions: true
    };
    console.log('Fetching page ' + pageCounter + '...');
    const response = UrlFetchApp.fetch(url, options);
    const statusCode = response.getResponseCode();
    if (statusCode !== 200) {
      console.error('API Error: ' + response.getContentText());
      break;
    }
    const json = JSON.parse(response.getContentText());
    const records = json.data || [];
    // Merge new records into our master list
    allRecords = allRecords.concat(records);
    // Update cursor variables
    nextPageToken = json.next_page_token || null;
    hasMore = json.has_more && nextPageToken !== null;
    pageCounter++;
  } while (hasMore);
  console.log('Total records retrieved: ' + allRecords.length);
  return allRecords;
}

This loop keeps spinning until has_more is false or the next_page_token disappears. The names used here (data, has_more, next_page_token, starting_after) are placeholders: every API names them differently, and some, like Stripe, expect the ID of the last record instead of a token, so map them to your API’s documentation. The JS Array concat method merges each new batch into the main in-memory array.

To test it, pick fetchAllCursorData in the function drop-down at the top of the editor and click Run. Approve the permissions on the first run. The Execution log should list Fetching page 1..., Fetching page 2... and so on, ending with Total records retrieved: and a count. This function only returns the records; Step 5 writes them to the sheet.

Step 3: Handle Offset-and-Limit Pagination

Older APIs and database wrappers usually rely on offset-and-limit pagination. You tell the API how many records to skip (the offset) and how many to return (the limit). Usually, the API also returns a total count, so you know when to stop.

You can work out the number of requests before you start, though offset queries can get slow on the API’s side once offsets are very high.

function fetchAllOffsetData() {
  let allRecords = [];
  let offset = 0;
  let totalRecords = null;
  let pageCounter = 1;
  while (totalRecords === null || offset < totalRecords) {
    const url = BASE_URL + '?limit=' + LIMIT + '&offset=' + offset;
    const options = {
      method: 'get',
      headers: { 'Authorization': 'Bearer ' + API_KEY },
      muteHttpExceptions: true
    };
    console.log('Fetching offset ' + offset + ' (Page ' + pageCounter + ')...');
    const response = UrlFetchApp.fetch(url, options);
    if (response.getResponseCode() !== 200) {
      console.error('Failed to fetch offset ' + offset);
      break;
    }
    const json = JSON.parse(response.getContentText());
    const records = json.results || [];
    allRecords = allRecords.concat(records);
    // Set total count on the first run
    if (totalRecords === null) {
      totalRecords = json.total_count || 0;
      console.log('Total records to fetch: ' + totalRecords);
    }
    offset += LIMIT;
    pageCounter++;
  }
  return allRecords;
}

Run fetchAllOffsetData the same way. The log first shows Total records to fetch: with the API’s count, then one line per page. As with the cursor loop, rename results and total_count to whatever your API returns.

Step 4: Resume Before the 6-Minute Limit

If your API has 10,000 records and takes 500ms per request, fetching everything takes under a minute. But if the API is slow (say, 2 seconds per request) and you have 100,000 records, the script hits the 6-minute limit and stops mid-run. You are left with a half-filled sheet and no record of where it stopped.

The fix is to save your progress (the last cursor) in PropertiesService, the script’s built-in key-value store. The function below tracks elapsed time, stops at about 5 minutes, writes what it has, saves the cursor, and creates a one-off time-based trigger that runs it again a minute later.

function fetchLargeDatasetWithTimeout() {
  const startTime = new Date().getTime();
  const maxExecutionTimeMs = 5 * 60 * 1000; // 5 minutes safety limit
  const properties = PropertiesService.getScriptProperties();
  // Resume from where we left off, or start fresh
  let cursor = properties.getProperty('LAST_CURSOR') || null;
  // The first run overwrites the sheet; resumed runs append to it
  const appendMode = cursor !== null;
  let batchRecords = [];
  let isFinished = false;
  // Remove the one-off trigger that started this run, if there is one
  clearResumeTrigger();
  while (!isFinished) {
    // Check if we are running out of time
    const currentTime = new Date().getTime();
    if (currentTime - startTime > maxExecutionTimeMs) {
      console.warn('Approaching timeout limit. Saving state and scheduling resume...');
      saveProgress(properties, cursor, batchRecords, appendMode);
      setupResumeTrigger();
      return;
    }
    let url = BASE_URL + '?limit=' + LIMIT;
    if (cursor) {
      url += '&starting_after=' + encodeURIComponent(cursor);
    }
    const response = UrlFetchApp.fetch(url, {
      headers: { 'Authorization': 'Bearer ' + API_KEY },
      muteHttpExceptions: true
    });
    if (response.getResponseCode() !== 200) {
      // Keep what we already fetched so the next run can pick up from here
      saveProgress(properties, cursor, batchRecords, appendMode);
      throw new Error('API error ' + response.getResponseCode() + '. Progress saved; run again to resume.');
    }
    const json = JSON.parse(response.getContentText());
    const records = json.data || [];
    batchRecords = batchRecords.concat(records);
    cursor = json.next_page_token || null;
    if (!cursor) {
      isFinished = true;
    }
  }
  // Finished: write the last batch and clear the saved position
  writeToSheet(batchRecords, appendMode);
  properties.deleteProperty('LAST_CURSOR');
  console.log('Sync complete!');
}
function saveProgress(properties, cursor, records, appendMode) {
  writeToSheet(records, appendMode);
  if (cursor) {
    properties.setProperty('LAST_CURSOR', cursor);
  }
}
function setupResumeTrigger() {
  const trigger = ScriptApp.newTrigger('fetchLargeDatasetWithTimeout')
    .timeBased()
    .after(1 * 60 * 1000) // Run again in about 1 minute
    .create();
  PropertiesService.getScriptProperties().setProperty('RESUME_TRIGGER_ID', trigger.getUniqueId());
}
function clearResumeTrigger() {
  // Delete only the one-off trigger this script created, never your other triggers
  const properties = PropertiesService.getScriptProperties();
  const resumeId = properties.getProperty('RESUME_TRIGGER_ID');
  if (!resumeId) return;
  ScriptApp.getProjectTriggers().forEach(trigger => {
    if (trigger.getUniqueId() === resumeId) {
      ScriptApp.deleteTrigger(trigger);
    }
  });
  properties.deleteProperty('RESUME_TRIGGER_ID');
}

Run fetchLargeDatasetWithTimeout once from the editor to start the job. Google asks for one extra permission the first time, because the script creates triggers. If the job is large, the log ends with Approaching timeout limit. Saving state and scheduling resume..., and a temporary trigger appears on the Triggers page. Each resumed run is listed under Executions, and the final one logs Sync complete!.

Each resumed run starts in a fresh execution with a new 6-minute window, so you can work through very large datasets without losing your place. Two ceilings still apply: triggered runs share a daily runtime quota (90 minutes on consumer accounts, 6 hours on Google Workspace), and a spreadsheet holds at most 10 million cells.

Step 5: Write to the Sheet in One Batch

A common mistake is calling sheet.appendRow() inside the pagination loop. Every call to the spreadsheet carries overhead, so a loop of 500 calls spends most of its time waiting on sheet updates.

Instead, turn the records into a single 2D array (a list of rows, each a list of cell values) in memory and write it with one setValues() call. This is usually many times faster than writing row by row. Paste this function into the same file; the resume function above already calls it:

function writeToSheet(records, appendMode) {
  if (records.length === 0) return;
  // Use a named tab: in a triggered run, getActiveSheet() is simply the first tab
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
  // Map JSON objects to 2D array matching your columns
  const rows = records.map(record => [
    record.id || '',
    record.email || '',
    record.created_at || '',
    record.status || ''
  ]);
  if (appendMode) {
    // Find the last row and append the block
    const lastRow = sheet.getLastRow();
    const range = sheet.getRange(lastRow + 1, 1, rows.length, rows[0].length);
    range.setValues(rows);
  } else {
    // Clear and overwrite the entire sheet
    sheet.clearContents();
    // Add headers
    sheet.getRange(1, 1, 1, 4).setValues([['ID', 'Email', 'Created At', 'Status']]);
    // Write data
    const range = sheet.getRange(2, 1, rows.length, rows[0].length);
    range.setValues(rows);
  }
}

Edit the record.id, record.email and other fields in the map to match your API, and change the header row to match. The overwrite branch clears the whole tab, which is why the function writes to the tab named in SHEET_NAME (create a tab called “API Data” or change the constant) rather than to whichever sheet happens to be active.

To write the output of the simple loops from Steps 2 and 3, call it with their result, for example writeToSheet(fetchAllCursorData(), false) inside a small function of your own. If several triggers can write at the same time, also prevent race conditions using LockService so they do not overwrite each other.

Step 6: Retry When the API Rate-Limits You

If you fetch data rapidly, you will eventually hit a rate limit. Most APIs answer with a 429 Too Many Requests status code when you cross the line, and if you keep sending requests some will block your token for a while.

A simple exponential backoff wrapper handles this. On a 429, it pauses with Utilities.sleep() and retries; if it fails again, it doubles the wait and tries once more.

function fetchWithRetry(url, options, retries = 3, delayMs = 1000) {
  for (let i = 0; i < retries; i++) {
    const response = UrlFetchApp.fetch(url, options);
    const statusCode = response.getResponseCode();
    if (statusCode === 200) {
      return response;
    }
    if (statusCode === 429) {
      console.warn('Rate limit hit. Retrying in ' + delayMs + 'ms...');
      Utilities.sleep(delayMs);
      delayMs *= 2; // Exponential backoff
      continue;
    }
    // For other errors, log and stop immediately
    console.error('Fetch failed with status ' + statusCode);
    break;
  }
  return null;
}

This helper replaces your raw UrlFetchApp.fetch() calls. It keeps your loops running through temporary rate limiting. Two things to remember: pass muteHttpExceptions: true in the options, otherwise UrlFetchApp throws on a 429 before the helper can react, and check for the null it returns when it gives up.

If It Still Doesn’t Work

  • Only the first page arrives: the response field names do not match your API, so the loop finds no next-page token or a total count of zero. Log response.getContentText() once and rename the fields in the code.
  • Every request fails with 401 or 403: the API_KEY script property is missing or misspelt, so the header says Bearer null. Also check whether your API expects a different header than Authorization: Bearer.
  • “TypeError: Cannot read properties of null” in writeToSheet: there is no tab with the name in SHEET_NAME. Create it or change the constant.
  • The job stops and never resumes: open Triggers to see whether the resume trigger exists, and Executions for errors. A failed API call saves progress and throws, so run the function again by hand to continue.
  • A new sync appends instead of starting over: an interrupted job left LAST_CURSOR behind, so the script thinks it is resuming. Delete that property under Project Settings > Script Properties to start fresh.

Frequently Asked Questions

How do I know if my API uses cursor or offset pagination?

Check the API’s pagination docs. If you see query parameters like page, offset or skip, it is offset-based. If you see parameters like starting_after, ending_before, next_cursor or pageToken, or a token in each response, it is cursor-based.

Why does Apps Script say “Exceeded maximum execution time”?

Your script ran past the 6-minute limit, which is the same on consumer and Google Workspace accounts. Split the work across several runs with the state-saving pattern in Step 4: save the cursor in PropertiesService and let a one-off trigger continue where the last run stopped.

Can I write data to the sheet row by row if I have a small dataset?

You can, but batching is still better. Even for 50 rows, one setValues() call is noticeably faster than 50 appendRow() calls, and the habit protects you when the dataset grows. It also leaves more of the 6-minute window for API requests.

How many records can Apps Script fetch in a day?

It depends on page size and quotas rather than a fixed record limit. A consumer account can make 20,000 URL fetches a day (100,000 on Workspace), and triggered runs share 90 minutes of runtime (6 hours on Workspace). The sheet itself stops at 10 million cells.

Next Steps

Adapt the field names to your API, run the cursor or offset loop once to confirm the page count, then switch to the resume pattern for the full sync. To push cleaned rows back out to another service, see how to send webhooks from Google Sheets with Apps Script.

all_in_one_marketing_tool