Skip to content

Snippets · 10 functions

Web request snippets

Each snippet is a complete function that calls a URL with UrlFetchApp, ready to paste into the Apps Script editor and adapt to your own API.

How to use these

Set up before you run

Copy a snippet into a script file, read its setup and notes, change the placeholder values, and save. For functions meant to run manually, choose the function name in the toolbar and press Run. Results appear in the Execution log unless the description says otherwise.

1

GET JSON and log a field

Fetches a public weather forecast, parses the JSON response, and logs one value out of it.

Code.gs
function logWeatherField() {
  const url = 'https://api.open-meteo.com/v1/forecast?latitude=47.6&longitude=-122.3&daily=temperature_2m_max&timezone=auto';
  const response = UrlFetchApp.fetch(url);
  const data = JSON.parse(response.getContentText());
  Logger.log('Max temperature: ' + data.daily.temperature_2m_max[0]);
}

2

Check the status code before parsing

Uses muteHttpExceptions so a failed request returns a response instead of throwing, then checks the status code first.

Code.gs
function fetchWithStatusCheck() {
  const url = 'https://api.example.com/items';
  const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
  const statusCode = response.getResponseCode();
  if (statusCode !== 200) {
    Logger.log('Request failed with status ' + statusCode);
    return;
  }
  const data = JSON.parse(response.getContentText());
  Logger.log('Items returned: ' + data.length);
}

Good to know. Without muteHttpExceptions, UrlFetchApp throws on an error status code (400 or higher) instead of returning it. Redirects are followed by default.

3

POST JSON with a payload and contentType

Sends a JSON object to an API by setting the method, contentType, and a stringified payload.

Code.gs
function postJsonPayload() {
  const url = 'https://api.example.com/items';
  const payload = { name: 'New item', quantity: 3 };
  const response = UrlFetchApp.fetch(url, {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify(payload)
  });
  Logger.log('Status: ' + response.getResponseCode());
}

4

Send a bearer token header read from script properties

Reads a saved API key from script properties and sends it as an Authorization header.

Code.gs
function fetchWithBearerToken() {
  const apiKey = PropertiesService.getScriptProperties().getProperty('API_KEY');
  if (!apiKey) throw new Error('Set an API_KEY script property before running this function.');

  const url = 'https://api.example.com/items';
  const response = UrlFetchApp.fetch(url, {
    headers: { Authorization: 'Bearer ' + apiKey }
  });
  Logger.log('Status: ' + response.getResponseCode());
}

Good to know. Never paste a real key into the code itself; store it as a script property from Project Settings instead.

5

Add query parameters with encodeURIComponent

Builds a URL with a search term and a limit, encoding the term so spaces and symbols do not break the request.

Code.gs
function fetchWithQueryParameters() {
  const baseUrl = 'https://api.example.com/items';
  const searchTerm = 'office supplies';
  const url = baseUrl + '?q=' + encodeURIComponent(searchTerm) + '&limit=20';
  const response = UrlFetchApp.fetch(url);
  Logger.log('Status: ' + response.getResponseCode());
}

6

Fetch several URLs at once

Uses UrlFetchApp.fetchAll to send several requests together instead of calling fetch in a loop.

Code.gs
function fetchSeveralUrlsAtOnce() {
  const requests = [
    { url: 'https://api.example.com/items/1' },
    { url: 'https://api.example.com/items/2' },
    { url: 'https://api.example.com/items/3' }
  ];
  const responses = UrlFetchApp.fetchAll(requests);
  responses.forEach((response, index) => {
    Logger.log('Request ' + (index + 1) + ' status: ' + response.getResponseCode());
  });
}

7

Download a file from a URL and save it to Drive

Fetches a file, converts the response to a blob, and saves that blob as a new file in Drive.

Code.gs
function saveUrlFileToDrive() {
  const url = 'https://api.example.com/reports/latest.pdf';
  const response = UrlFetchApp.fetch(url);
  const blob = response.getBlob();
  const file = DriveApp.createFile(blob);
  Logger.log('Saved to Drive: ' + file.getName());
}

Good to know. This saves the file in the root of Drive; move it into a specific folder if you need to keep Drive tidy.

8

Read response headers

Reads the HTTP response headers as an object and logs one of them.

Code.gs
function logResponseHeaders() {
  const url = 'https://api.example.com/items';
  const response = UrlFetchApp.fetch(url);
  const headers = response.getHeaders();
  Logger.log('Content-Type: ' + headers['Content-Type']);
}

9

Handle a failed request with a clear error message

Checks the response status and throws a specific error naming the URL and status code, so the failure is easy to trace.

Code.gs
function fetchOrThrowClearError() {
  const url = 'https://api.example.com/items';
  const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
  const statusCode = response.getResponseCode();
  if (statusCode !== 200) {
    throw new Error('Request to ' + url + ' failed with status ' + statusCode + '.');
  }
  Logger.log('Request succeeded.');
}

10

Log the first 200 characters of a response body while debugging

Prints only the start of a response body, enough to check its shape without flooding the execution log.

Code.gs
function logResponsePreview() {
  const url = 'https://api.example.com/items';
  const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
  const body = response.getContentText();
  Logger.log(body.slice(0, 200));
}

Good to know. Remove or comment out this preview log before sharing the script, since a response can include private data.

Keep going

See these in a complete task

All snippet collections