Introduction to UrlFetchApp

UrlFetchApp is Apps Script's built-in class for making HTTP requests. With it, you can call any external REST API, fetch web pages, send webhooks, or interact with third-party services directly from your script.

Making a Basic GET Request

function basicGetRequest() { var url = "https://httpbin.org/get"; var response = UrlFetchApp.fetch(url); Logger.log("Status code: " + response.getResponseCode()); Logger.log("Body: " + response.getContentText()); }

Reading the Response

The HTTPResponse object has several useful methods:

function readResponse() { var response = UrlFetchApp.fetch("https://httpbin.org/get"); Logger.log("Status: " + response.getResponseCode()); // e.g. 200 Logger.log("Headers: " + JSON.stringify(response.getHeaders())); Logger.log("Body: " + response.getContentText()); }

Parsing a JSON Response

Most modern APIs return JSON. Use JSON.parse() to convert the response text into a JavaScript object:

function parseJsonResponse() { var response = UrlFetchApp.fetch("https://httpbin.org/json"); var json = JSON.parse(response.getContentText()); Logger.log("Slideshow title: " + json.slideshow.title); }

Setting Request Headers

Pass headers using the options object:

function requestWithHeaders() { var options = { method: "GET", headers: { "Accept": "application/json", "X-App-Name": "Acme Corp Sales Tracker" } }; var response = UrlFetchApp.fetch("https://httpbin.org/headers", options); Logger.log(response.getContentText()); }

Handling HTTP Errors Gracefully

By default, Apps Script throws an exception on 4xx/5xx responses. Use muteHttpExceptions: true to handle errors in your own code:

function safeRequest() { var options = { method: "GET", muteHttpExceptions: true }; var response = UrlFetchApp.fetch("https://httpbin.org/status/404", options); var code = response.getResponseCode(); if (code === 200) { Logger.log("Success: " + response.getContentText()); } else if (code === 404) { Logger.log("Not found. Check the URL."); } else if (code === 401) { Logger.log("Unauthorised. Check your API key."); } else { Logger.log("Unexpected error: " + code); } }

Always use muteHttpExceptions: true in production scripts so a failed API call doesn't crash your entire workflow.

Checking URL Validity Before Fetching

function fetchIfReachable(url) { try { var response = UrlFetchApp.fetch(url, { muteHttpExceptions: true }); if (response.getResponseCode() === 200) { return JSON.parse(response.getContentText()); } Logger.log("Bad status: " + response.getResponseCode()); return null; } catch (e) { Logger.log("Request failed: " + e.message); return null; } }

Request Options Reference

OptionDescription
method"GET", "POST", "PUT", "PATCH", "DELETE"
headersObject of request headers
payloadRequest body (string or object for POST/PUT)
contentTypeContent-Type header shorthand (e.g. "application/json")
muteHttpExceptionsIf true, don't throw on error status codes
followRedirectsIf false, don't follow HTTP redirects (default: true)