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
codein the body and document it for clients. - Always
try/catchat 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.
