An AI-checked expense approval flow in Google Sheets works by having a script read each new expense row, send the relevant fields to a model for a policy check, and write a flag back — but the most common version of this tutorial breaks in production because it tries to do that from a simple onEdit(e) trigger, which Google’s own documentation says can’t call a service that requires authorization. An external API call through UrlFetchApp needs that authorization, so the fix isn’t a better prompt or a different AI provider — it’s switching to an installable trigger before you write a single line of AI-calling code, which is a five-minute setup step most tutorials skip entirely because it isn’t about the AI part at all.
Step 1: Understand why the obvious approach fails first
Google’s Apps Script documentation on triggers is specific about what a simple trigger — a reserved function name like onEdit(e) that runs automatically with no setup — can and can’t do. It can only modify the file it’s bound to, it can’t use any service that requires authorization, and it can’t run longer than 30 seconds. Calling an external AI API through UrlFetchApp falls squarely into “requires authorization,” which is why developers consistently run into a “you do not have permission to call UrlFetchApp.fetch” error the moment they try to wire an API call directly into onEdit. This isn’t an edge case or a bug in your code — it’s the documented, expected behavior of a simple trigger, and it’s the first obstacle this tutorial needs to get past before the actual AI logic matters at all.
Step 2: Set up an installable trigger instead
An installable trigger has to be set up explicitly rather than just existing because of its function name, and that setup step is what grants it the authorization a simple trigger never gets. From the Apps Script editor, create a separate function and bind it with ScriptApp.newTrigger():
function createOnEditTrigger() {
ScriptApp.newTrigger('checkExpenseWithAI')
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onEdit()
.create();
}
Run createOnEditTrigger once manually from the editor. Google will prompt you to authorize the script at that point — that authorization dialog is the step a simple trigger skips entirely, and it’s also why it can do things a simple trigger can’t.
Step 3: Write the function that actually checks the expense
With the installable trigger in place, checkExpenseWithAI(e) can read the edited row, call an AI API, and write a result back into the sheet, all without hitting the authorization wall a simple trigger would run straight into:
function checkExpenseWithAI(e) {
const sheet = e.range.getSheet();
const row = e.range.getRow();
// Only run on the columns that matter — amount and category
if (e.range.getColumn() > 4) return;
const amount = sheet.getRange(row, 2).getValue();
const category = sheet.getRange(row, 3).getValue();
const note = sheet.getRange(row, 4).getValue();
const prompt = `Expense: $${amount}, category: "${category}", note: "${note}".
Flag ONLY if this looks like it violates a standard expense policy
(e.g. alcohol, amounts over $500 without a note, personal items).
Reply with exactly one word: OK or FLAG, then a 1-sentence reason.`;
const response = callAIModel(prompt); // wraps UrlFetchApp.fetch
sheet.getRange(row, 5).setValue(response);
}
Writing the result with setValue() is safe here specifically because Apps Script’s documentation confirms that calling Range.setValue() doesn’t itself fire onEdit — if it did, this would re-trigger itself in a loop every time it wrote a result back to the sheet.
Step 3b: Keep the API key out of the script itself
Pasting an API key directly into a script file is a common shortcut in quick tutorials, and it’s also how keys end up committed to version history or shared the moment someone copies the script to a new sheet. Apps Script’s PropertiesService exists specifically to avoid this — store the key once, outside the script body, and read it at call time:
// Run once, manually, from the editor — never commit this call itself
function setApiKey() {
PropertiesService.getScriptProperties().setProperty('AI_API_KEY', 'your-key-here');
}
function callAIModel(prompt) {
const apiKey = PropertiesService.getScriptProperties().getProperty('AI_API_KEY');
const response = UrlFetchApp.fetch('https://api.your-ai-provider.com/v1/messages', {
method: 'post',
contentType: 'application/json',
headers: { 'Authorization': 'Bearer ' + apiKey },
payload: JSON.stringify({ prompt: prompt, max_tokens: 60 }),
muteHttpExceptions: true
});
return response.getContentText();
}
setApiKey() is a function you run once from the editor and then never call again — it’s not part of the trigger flow, it’s a one-time setup step, the same way createOnEditTrigger() was. muteHttpExceptions: true matters too: without it, a failed API call throws an exception that can silently stop the rest of your onEdit logic from running, which is a confusing way to discover a rate limit or an expired key.
Step 4: Respect the 30-second ceiling, even on the installable trigger
Switching to an installable trigger lifts the authorization restriction, but it’s worth checking current execution-time limits for triggered functions before you assume a slow model response is safe — a model call that occasionally takes longer than expected is a realistic way for this exact function to start failing silently on some rows and not others. Keep the prompt short, ask for a one-word-plus-one-sentence answer rather than a long explanation, and consider batching: run the check on a timer every few minutes over all unflagged rows instead of synchronously on every single edit, which also protects you if someone pastes in fifty rows of expenses at once and fires fifty near-simultaneous edits that would otherwise all try to call the model within the same few seconds.
Step 5: Don’t let the AI’s flag be the approval
The flag column this script writes is a triage signal, not a decision. Writing “FLAG” or “OK” into a cell is the AI equivalent of a draft sitting in a review queue, and the same reasoning behind putting a review step between an agent’s draft output and the moment it actually takes effect applies directly here: nothing in this script should auto-approve a reimbursement or auto-send a payment based on the word “OK” appearing in a cell. Keep a human clearing the flagged rows, and treat an unflagged row as “nothing obvious jumped out,” not as “verified correct.”
Likely errors and how to actually fix them
- “You do not have permission to call UrlFetchApp.fetch” — you’re still calling the AI model from a simple trigger. Confirm the function name isn’t literally
onEdit, and that you ran the installable trigger’s setup function manually at least once to grant authorization. - The flag column never updates, with no error shown — check whether the edit happened in a column your
if (e.range.getColumn() > 4) return;guard is filtering out, or whether the row-paste scenario fired the trigger once per cell rather than once per row, leaving most of those calls short-circuited by the same guard. - The script works when you test it manually but not when a colleague edits the sheet — installable triggers run with the authorization of whoever created them, not the person editing the sheet. If your AI provider’s key or quota is tied to your own account, every edit anyone makes is using your credentials and your usage limits, which is worth knowing before a shared team sheet with a dozen active contributors quietly burns through your own personal API quota without anyone realizing whose account was paying for it.
- Everything works, then stops after a few weeks with no code changes — Apps Script triggers are subject to quotas that reset daily, and a high-volume sheet can exhaust the trigger-execution quota before the day is over. Check the quota page in your project settings before you assume the AI provider, the script, or the sheet itself has broken.
Step 6: Test it the way you’d test any approval gate — by trying to break it
Before this runs on real expense data, enter a few rows you already know should flag — an alcohol purchase, a $900 entry with no note, something personal disguised with a vague description — and a few that clearly shouldn’t. If the script flags the obvious violations and leaves the clean entries alone, it’s doing its job as a triage layer. If it misses an obvious violation, that’s a prompt problem worth fixing before it ever sees a real reimbursement request, not after a bad one gets approved because a busy human reviewer trusted an “OK” in a flag column that wasn’t actually earned. The same testing discipline that applies to any AI agent wired into the Google Workspace APIs applies here — test the failure cases deliberately, rather than waiting for one to show up in production.
If you’re already using AI prompts to pull insights out of spreadsheet data, this is the same underlying pattern applied to a gate instead of a summary: read structured rows, call a model with a narrow, specific question, and write a narrow, specific answer back — never a free-form paragraph where a single word would do, and never, under any configuration of this script, an action that a human didn’t actually and knowingly approve first.
Featured image: Unicom 141P Calculator, public domain, via Wikimedia Commons.
Source: Google’s Apps Script triggers documentation.



