Google Apps Script fetch JSON


This post goes over how to fetch JSON with Google Apps Script.

Prerequisites

Create a Google Apps Script in one of two ways:

  1. Google Drive > New > More > Google Apps Script
  2. Google Sheets > Extensions > Apps Scripts

Google Apps Script

Perform a GET request to https://example.com/:

function getHTML() {
  const url = 'https://example.com/';
  const response = UrlFetchApp.fetch(url);
  const html = response.getContentText();
  console.log(html);
}

Perform a GET request to https://httpbin.org/json:

function getJSON() {
  const url = 'https://httpbin.org/json';
  const response = UrlFetchApp.fetch(url);
  const json = JSON.parse(response.getContentText());
  console.log(json);
}

Perform a POST request to https://httpbin.org/anything:

function postJSON() {
  const url = 'https://httpbin.org/anything';
  const params = {
    method: 'post',
    payload: { foo: 'bar' },
  };
  const response = UrlFetchApp.fetch(url, params);
  const json = JSON.parse(response.getContentText());
  console.log(json);
}

Notice in the logs how the payload shows up in the form field because the contentType defaults to 'application/x-www-form-urlencoded'.

To properly POST JSON:

 function postJSON() {
   const url = 'https://httpbin.org/anything';
   const params = {
     method: 'post',
+    contentType: 'application/json',
-    payload: { foo: 'bar' },
+    payload: JSON.stringify({ foo: 'bar' }),
   };
   const response = UrlFetchApp.fetch(url, params);
   const json = JSON.parse(response.getContentText());
   console.log(json);
 }

The payload now shows up in the data field in the logs.

Check out UrlFetchApp.fetch for more details.

Script

Here’s a reusable script to fetch JSON:

/**
 * @param {string} url
 * @param {Record<string, any>|undefined} params
 * @returns {any}
 */
function fetchJSON(url, params) {
  const response = UrlFetchApp.fetch(url, {
    contentType: 'application/json',
    method: 'post',
    ...params,
    payload: JSON.stringify(params.payload),
  });
  return JSON.parse(response.getContentText());
}

And it can be called like so:

const json = fetchJSON('https://httpbin.org/anything', {
  foo: 'bar',
});
console.log(json);


Please support this site and join our Discord!