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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
- Task guide Import data from a web API into Sheets
The script reads Open-Meteo once and replaces only Forecast!A1:C12 after checking the response and the destination. It preserves the source and licence links beside the forecast.
- Task guide Check a website and alert when it is down
An hourly trigger fetches one address. The script remembers the last result in a script property, so a long outage produces one alert instead of one every hour.
- Task guide Store settings with PropertiesService
PropertiesService.getScriptProperties() stores small key-value settings with the Apps Script project. Save a setting once with setProperties(), then read it on every run with getProperty().
- Basics Google Apps Script quotas and limits
Google caps how long one run may take and how much your scripts may do in a day. Knowing the caps changes how you write anything that touches a lot of rows.
- Basics Apps Script permissions and authorization
Before a script can read your sheet or send your mail, you give it permission to access a list of OAuth scopes. This page walks through each authorization screen, explains @OnlyCurrentDoc, and shows how to revoke access.
- Basics Common Apps Script errors and what they mean
Apps Script error messages name the failure directly, from TypeError: Cannot read properties of null (reading 'getRange') to ReferenceError and quota limits. Find the exact message below for the cause and fix.