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
- muteHttpExceptions lets the code read the error body instead of a bare exception.
- Keep API keys in Script Properties, never in the code.
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