Author: By Raj
Part of our Apps Script API Integrations guides. Need this built for your team? Hire a Google Apps Script developer.
Estimated reading time: 10 minutes
Call the OpenAI API from Google Apps Script (with Examples)
OpenAI models can classify support tickets, draft email replies, or summarize Sheet notes when called from Apps Script via UrlFetchApp to api.openai.com/v1/chat/completions.
Store OPENAI_API_KEY in Script Properties. Batch rows with rate awareness, GPT calls are slower and costlier than spreadsheet formulas.
Never send regulated PII without review. Log prompt hashes, not full customer text, in production. See /blog/apps-script-rest-api-guide for JSON POST patterns.
Chat Completions request shape
POST JSON with model, messages array [{role:'user', content: prompt}], and max_tokens cap. Parse choices[0].message.content.
Use temperature 0 for classification, higher for creative drafts.
Sheet column batching
Process N rows per run starting at cursor row in Properties. Write results to column G while status column F shows Pending/Done/Error.
Skip rows where input cell empty to save tokens.
Cost and token control
Truncate input text to 2k chars with honest ellipsis. Summarize long threads in a first pass with cheaper mini models if available.
Track monthly spend in a Billing sheet updated from OpenAI usage API if finance requires.
Safety and human review
Flag outputs needing human approval before MailApp sends customer-facing email. Use data validation Approved? column.
Add system message instructing model not to invent refund policies.
Example code
function classifyTicket(note) {
const key = PropertiesService.getScriptProperties().getProperty('OPENAI_API_KEY');
const res = UrlFetchApp.fetch('https://api.openai.com/v1/chat/completions', {
method: 'post',
contentType: 'application/json',
headers: { Authorization: 'Bearer ' + key },
payload: JSON.stringify({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: 'Return one label: Billing, Technical, Sales.' },
{ role: 'user', content: note },
],
max_tokens: 20,
}),
});
return JSON.parse(res.getContentText()).choices[0].message.content.trim();
}| Approach | Best for | Tradeoff |
|---|---|---|
| Apps Script native | Google Workspace-centric workflows | 6-min limit, quotas |
| Zapier / Make | No-code, many connectors | Per-task cost, vendor lock-in |
| Python + Cloud | Heavy data / ML | Hosting cost, separate auth |
| API integration services | Production custom logic | Build cost, you own code |
FAQ
Can I use Assistants API from Apps Script?
Yes with longer polling for run status. Simpler flows use chat completions directly for Sheet row enrichment.
Will this hit execution time limits?
Many sequential API calls will. Process 20 rows per trigger with continuation, see /blog/google-apps-script-execution-time-limit.
How to handle API 429?
Exponential backoff and reduce batch size. Cache identical prompts with CacheService keyed by hash.
Can Gemini replace OpenAI in same pattern?
Swap URL and payload for Google's Generative Language API with appropriate key, architecture identical.
Is customer data allowed?
Follow OpenAI enterprise terms and your DPA. Many teams anonymize IDs before sending text.
Need this done for you? I handle this as part of my consulting work, fixed-price quote within 24 hours.
Book a call with Raj →Get the full Call the OpenAI API from Google Apps Script (with Examples) script template
I'll email you a production-ready, commented version you can deploy in 10 minutes.
Continue reading
API Integrations
Connect Shopify API to Google Sheets with Apps Script
API Integrations
Send automated SMS from Google Sheets (Twilio): Production Apps Script Guide
API Integrations
Google Apps Script vs Zapier vs Make: Which Should You Use?
From another topic
How to Automate Google Sheets with Apps Script (Beginner Guide) →Need help with this? I handle this as part of my Apps Script API Integrations service.
Shopify, Stripe, Slack, HubSpot, webhooks, and REST API connections.
See how it works →