Hand-building ?a=1&b=2 is how spaces and ampersands sneak into broken UrlFetch GETs. buildQueryString walks a plain object, skips null/empty, and encodeURIComponents keys and values. Drop it onto any base URL before UrlFetchApp.fetch.
What you'll need
- A base URL without a query (or strip an existing one first)
- A plain object of params (strings/numbers/booleans)
How to use this snippet
function buildQueryString(params) {
params = params || {};
var parts = [];
Object.keys(params).forEach(function (key) {
var v = params[key];
if (v == null || v === '') return;
parts.push(
encodeURIComponent(key) + '=' + encodeURIComponent(String(v))
);
});
return parts.length ? '?' + parts.join('&') : '';
}
function fetchPage(q, page) {
var url =
'https://api.example.com/search' +
buildQueryString({ q: q, page: page, format: 'json' });
return UrlFetchApp.fetch(url, { muteHttpExceptions: true });
}
Tips
- Arrays: decide up front (
ids=1&ids=2vs comma-join) — this helper treats values as scalars. - Don't double-encode: pass raw strings, not already-encoded ones.
- Pair with
retryUrlFetchwhen the API rate-limits.
Happy Coding.
