You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Apps Script中用UrlFetchApp遍历Moneybird API多页联系人?

How to Fetch All Contacts from Moneybird API with Pagination in Google Apps Script

Hey there! Let's tackle this pagination issue with the Moneybird API in Google Apps Script. The core idea is to keep checking for the next page link in the response headers and keep fetching until there are no more pages left. Here's how you can adjust your code to make this work smoothly:

First, let's update your function to loop through all pages and collect all contacts:

function listAllContacts() { 
  var allContacts = []; // Store all contacts from every page
  var options = { 
    'method': 'GET', 
    'contentType': 'application/json', 
    'muteHttpExceptions': true, // Lets us handle errors gracefully instead of crashing
    'headers': { 
      'Authorization': 'Bearer ' + SERVICE.getAccessToken() 
    }, 
  }; 
  var currentUrl = 'https://moneybird.com/api/v2/'+ADMIN_ID+'/contacts.json'; 

  // Keep fetching until there's no next page URL
  while (currentUrl) {
    try {
      var response = UrlFetchApp.fetch(currentUrl, options); 
      var responseCode = response.getResponseCode();

      // Stop if the request fails (non-200 status code)
      if (responseCode !== 200) {
        console.log(`Request failed with code ${responseCode}: ${response.getContentText()}`);
        break;
      }

      // Add current page's contacts to our full list
      var pageData = JSON.parse(response.getContentText());
      allContacts = allContacts.concat(pageData);

      // Extract the next page URL from the Link header
      var headers = response.getAllHeaders();
      var linkHeader = headers["Link"];
      currentUrl = null; // Reset to exit loop unless we find a next link

      if (linkHeader) {
        // Split the header into individual link entries
        var links = linkHeader.split(',');
        for (var link of links) {
          var linkParts = link.trim().split(';');
          var pageUrl = linkParts[0].replace(/[<>]/g, ''); // Remove angle brackets around the URL
          var relAttribute = linkParts[1]?.trim();

          // Check if this is the "next" page link
          if (relAttribute === 'rel="next"') {
            currentUrl = pageUrl;
            break; // No need to check other links once we find next
          }
        }
      }

      console.log(`Fetched ${pageData.length} contacts | Total so far: ${allContacts.length}`);

    } catch (error) {
      console.log(`Error fetching data: ${error.message}`);
      break;
    }
  }

  console.log(`All done! Total contacts fetched: ${allContacts.length}`);
  return allContacts; 
}

Key Details & Improvements:

  • Centralized storage: The allContacts array accumulates data from every page, so you end up with one complete list.
  • Robust loop logic: The while (currentUrl) loop runs as long as we have a valid next page URL to fetch.
  • Error handling:
    • muteHttpExceptions: true lets us catch and log non-success responses instead of the script crashing immediately.
    • A try/catch block handles unexpected issues like network errors.
  • Link header parsing: The Moneybird API returns links in the format <url>; rel="next"—we split this header, clean up the URL, and check for the rel="next" attribute to find the next page.
  • Progress tracking: Console logs help you monitor how many contacts you've fetched at each step, which is great for debugging.

Additional Tips:

  • Rate limits: If you're fetching hundreds of pages, add a small delay between requests with Utilities.sleep(1000) (1 second) to avoid hitting Moneybird's rate limits.
  • Rate limit headers: Keep an eye on headers like X-RateLimit-Limit and X-RateLimit-Remaining to adjust your request timing dynamically if needed.
  • Edge cases: The code defaults to currentUrl = null, so the loop will exit cleanly even if the Link header exists but has no next rel.

内容的提问来源于stack exchange,提问作者amrz one

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:43:14