JSON OK / ERR helpers for Web Apps

doGet / doPost handlers stay readable when every success and failure returns the same JSON shape. jsonOk / jsonErr wrap ContentService so callers always see { ok: true, data } or { ok: false, error, code }.

What you'll need

  • A deployed Apps Script web app (doGet / doPost)
  • Callers that expect JSON (fetch, Zapier, another script)

How to use this snippet

function jsonOk(data) { return ContentService .createTextOutput(JSON.stringify({ ok: true, data: data })) .setMimeType(ContentService.MimeType.JSON); } function jsonErr(message, code) { return ContentService .createTextOutput(JSON.stringify({ ok: false, error: message, code: code == null ? 400 : code })) .setMimeType(ContentService.MimeType.JSON); } function doGet(e) { try { var id = e && e.parameter && e.parameter.id; if (!id) return jsonErr('Missing id', 400); return jsonOk({ id: id }); } catch (err) { return jsonErr(err.message || String(err), 500); } }

Tips

  • Apps Script web apps don't set HTTP status codes the way Express does — put a code in the body and document it for clients.
  • Always try/catch at the edge so stack traces don't become HTML error pages for API callers.
  • Pair with a clear Execute-as choice (me vs user) so the handler can actually see the sheet.

Soft tip: when the auth model feels fuzzy, Co-Pilot can leave a plain-English note next to the deploy settings. 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