The CRM sync ran fine for weeks. Then one row had a blank email, the API answered 400 Bad Request: invalid_parameter, and the job stopped halfway, leaving 200 rows unsent. Or worse: the API accepted the blank and created a contact with no email, which someone had to clean up by hand.
The API was never the right place to discover that a field was empty. The sheet already knew. Preflight each row: check the fields the call needs, tell a human what’s missing in plain words, and only call the API for rows that are ready.
TL;DR
- Keep a
REQUIREDlist of the columns the API call actually uses - Before calling, check each row with
assertRequiredKeys(row, REQUIRED). You get{ ok, missing } - Missing anything? Write “Needs info: Email, Amount” to Status and skip the call
- Blank and whitespace-only cells count as missing;
0andfalsedon’t - Ready rows go through; one bad row never stops the batch
Using the Apps Script editor a lot? NitroGAS drops free themes & snippets right into script.google.com — optional Co-Pilot when you want a boost.
Why preflight beats “let the API tell us”
- API errors are written for developers:
invalid_parameter: contact.email_address. Ops can’t act on that - Some APIs accept bad data and you find out later, in their dashboard
- Every failed call still costs quota and time, and some APIs rate-limit after errors
- Failing mid-batch leaves the sheet half-sent and hard to reason about
We covered the wording side of this in Give non-technical teammates errors they can act on. This guide is the specific case of “don’t even call the API until the row is ready.”
What not to do
- Don’t check “required” fields in a different place from where you build the payload; they’ll drift apart
- Don’t write
Error: TypeError…to the Status column; write what to fill in - Don’t
throwon the first bad row in a batch job; mark it and move on - Don’t treat
0as missing by accident (if (!row.Amount)); a $0 invoice can be real
Workflow
1. Read rows as header-keyed objects (with _row)
2. REQUIRED = the fields the payload uses
3. For each row: check → missing? Status = "Needs info: …" → skip
4. Ready rows: build payload → call API → Status = "Sent" (or the API's error, translated)
5. Toast / log: N sent, M need info
The preflight loop
// The fields the payload below actually uses. Change both together.
var CRM_REQUIRED = ['Email', 'First name', 'Plan', 'Amount'];
function pushLeadsToCrm() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Leads');
var values = sheet.getDataRange().getValues();
var headers = values.shift().map(function (h) { return String(h).trim(); });
var statusCol = headers.indexOf('Status') + 1;
if (!statusCol) throw new Error('Leads tab needs a Status column');
var sent = 0, needsInfo = 0, failed = 0;
values.forEach(function (r, i) {
var row = { _row: i + 2 };
headers.forEach(function (h, c) { if (h) row[h] = r[c]; });
if (row.Status === 'Sent') return; // already done
// 1. Preflight: is everything the API needs actually there?
var check = assertRequiredKeys(row, CRM_REQUIRED);
if (!check.ok) {
sheet.getRange(row._row, statusCol).setValue('Needs info: ' + check.missing.join(', '));
needsInfo++;
return; // no API call for this row
}
// 2. Ready: build the payload from the SAME fields
try {
callCrm_({
email: String(row.Email).trim(),
first_name: String(row['First name']).trim(),
plan: row.Plan,
amount: Number(row.Amount)
});
sheet.getRange(row._row, statusCol).setValue('Sent');
sent++;
} catch (err) {
sheet.getRange(row._row, statusCol).setValue('CRM said no: ' + friendlyApiError_(err));
failed++;
}
});
ss.toast(sent + ' sent · ' + needsInfo + ' need info · ' + failed + ' failed', 'CRM sync', 8);
}
assertRequiredKeys is the whole preflight: it returns the list of missing keys, treating '', ' ', null and undefined as missing and keeping 0 / false as real values.
Write statuses people can act on
Compare:
Error: Exception: Request failed for https://api.example.com returned code 400
Needs info: Email, Amount
The second one tells ops exactly which cells to fill. Once they fill them, the next run picks the row up automatically (Status isn’t Sent, and the check passes).
Two small upgrades worth making:
- Use the column names people see. The keys come from the header row, so “First name” in the status matches the column they’ll look for.
- Highlight it. Conditional formatting on Status: text starts with “Needs info” → amber. The backlog is visible at a glance.
Go one step past “present”
Presence is the first gate. A couple of format checks catch the next most common problems:
function formatProblems_(row) {
var problems = [];
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(row.Email).trim())) problems.push('Email looks wrong');
if (isNaN(Number(row.Amount))) problems.push('Amount must be a number');
return problems;
}
Run it after assertRequiredKeys passes, and write its messages to Status the same way.
Fail loud in helpers, gently in batches
Inside a single-purpose helper (build one invoice, one payload), throwing is fine. It stops bad data at the boundary:
assertRequiredKeys(payload, ['id', 'email'], { throwOnMissing: true, label: 'Invoice ' + payload.id });
In a batch loop, return-and-mark is kinder: one incomplete row shouldn’t block 199 good ones.
Failure modes worth naming
- Header renamed (“Email” → “Email address”): every row shows “Needs info: Email.” Annoying but loud. Better than silently sending blanks.
- Trailing spaces in headers: trim headers when building row objects (the loop above does).
- Formulas returning
"": they count as missing, which is usually right. - Required depends on another field (VAT number only for EU): handle that with a small
ifbefore the check, adding the conditional field to the list. - Status column overwritten by ops: protect it, or have the script own a separate “Sync status” column.
Soft Co-Pilot note
NitroGAS keeps assertRequiredKeys a search away in the editor. Paste the function that builds your API payload, and Co-Pilot can list the fields it really uses, draft the REQUIRED array, and write friendly “Needs info” statuses. You still decide what counts as required. Free core; Co-Pilot is a pass you grab when you want the draft.
Closing checklist
-
REQUIREDlist sits next to the payload builder - Every row preflighted before the API call
- Missing fields → “Needs info: …” in Status, call skipped
- Ready rows sent; failures translated, not raw
- Toast/log shows sent / needs info / failed counts
Happy Coding!


