GAS AI BuilderApps Script Assistant Sign in

Call an API with retries

Apps Script recipes › APIs, cache and settings

Calls an address, reads JSON, and tries again after a short wait when the service is busy (429 or 5xx).

File Code.gs

function fetchJson_(url, options) {
  const opts = Object.assign({ muteHttpExceptions: true, contentType: 'application/json' }, options || {});
  if (opts.payload && typeof opts.payload !== 'string') opts.payload = JSON.stringify(opts.payload);
  for (let attempt = 0; ; attempt++) {
    const res = UrlFetchApp.fetch(url, opts);
    const code = res.getResponseCode();
    if (code < 300) return JSON.parse(res.getContentText() || 'null');
    if ((code === 429 || code >= 500) && attempt < 3) {
      Utilities.sleep(1000 * Math.pow(2, attempt));
      continue;
    }
    throw new Error(`${url} answered ${code}: ${res.getContentText().slice(0, 300)}`);
  }
}

function getRates() {
  const key = PropertiesService.getScriptProperties().getProperty('API_KEY');
  return fetchJson_('https://api.example.com/rates', { headers: { Authorization: 'Bearer ' + key } });
}

Good to know

Let the AI put it in your appGAS AI Builder knows every recipe here. Describe your app and it uses this code where it fits, in a Google Apps Script project in your own Drive.

Use it in a project

More in APIs, cache and settings

Make slow reads fast with a cacheKeeps the result of a slow read for a few minutes, so a page that opens often doesn't read the whole sheet each time.Keep settings and secrets out of the codeScript Properties hold API keys and settings; a setup function asks for them once.