Build a Query String for UrlFetch

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=2 vs comma-join) — this helper treats values as scalars.
  • Don't double-encode: pass raw strings, not already-encoded ones.
  • Pair with retryUrlFetch when the API rate-limits.

Happy Coding.

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free themes and snippets — plus optional Co-Pilot when you want a boost (1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension