メインコンテンツにスキップ

fetch-app

UrlFetchApp with retries and more

AI Summary

FetchApp

Google Apps Script library that extends UrlFetchApp with advanced HTTP features such as retries, delays and callbacks.

Target Users

Intermediate-to-advanced GAS developers who need reliable HTTP communication for API integrations or webhooks.

Problems Solved

Implementing robust HTTP requests with retry logic and back-off in GAS projects is repetitive and error-prone.

Tags

Main Features

1
Status-code based retry control

Define `maxRetries` along with `successCodes` or `retryCodes` to flexibly decide when to repeat or stop requests.

2
Linear or exponential back-off delays

Configure `delay` and `delayFactor` to wait a fixed interval or exponentially increasing time between retries.

3
Failure callbacks for custom handling

Use `onRequestFailure` and `onAllRequestsFailure` to run custom logic such as logging or throwing errors.

4
Type hints & automatic logging

Copying the code gives full IDE autocompletion for `params`/`config`, and failed attempts are logged automatically.

Usage Examples

Sample: Call an API with retries

function callApiWithRetry() {
  // Target API endpoint
  const url = 'https://api.example.com/data';
  
  // Standard UrlFetchApp parameters
  const params = {
    method: 'get',
    // FetchApp defaults to muteHttpExceptions: true
    muteHttpExceptions: true
  };

  // FetchApp configuration
  const config = {
    maxRetries: 3,                // Retry up to three times
    retryCodes: [500, 502, 503],  // Retry on server errors only
    delay: 1000,                  // Start with 1-second delay
    delayFactor: 2                // Exponential back-off
  };

  // Execute the request
  const response = FetchApp.fetch(url, params, config);

  // Handle the response
  const data = JSON.parse(response.getContentText());
  Logger.log(data);
}

The snippet replaces UrlFetchApp with FetchApp, retries up to three times on server errors using exponential back-off, and logs the returned JSON.