If you're looking to connect OpenRouter's API to Google Sheets, you've come to the right place. I recently built a solution for this, and I'm going to show you how to get started with the basics.
Why Connect OpenRouter to Google Sheets?
OpenRouter gives you access to dozens of AI models (OpenAI, Claude, Gemini, DeepSeek, and more) through a single API. When you combine that with Google Sheets' automation capabilities, you can automate AI-powered tasks like content generation, data enrichment, and text analysis—all directly in your spreadsheets.
What You'll Need
Before we start, make sure you have:
- A Google Sheets account
- An OpenRouter API key
- Basic knowledge of Google Apps Script (we'll be using their scripting feature)
The Basic Connection
Here's the core of how I connect OpenRouter to Google Sheets. The key is using Google Apps Script's UrlFetchApp.fetch()
function to make API calls:
function sendToOpenRouter(prompt, apiKey, model) {
var endpoint = 'https://openrouter.ai/api/v1/chat/completions';
var payload = {
model: model,
messages: [
{ role: 'user', content: prompt }
],
max_tokens: 1000,
temperature: 0.7
};
var options = {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload),
headers: {
'Authorization': 'Bearer ' + apiKey
},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(endpoint, options);
var json = JSON.parse(response.getContentText());
return json.choices[0].message.content;
}
This function takes your prompt, sends it to OpenRouter, and returns the AI's response. Simple as that.
A Quick Example
Let's say you have a Google Sheet with a "Prompt" column and you want to fill an "Output" column with AI responses. Here's how you'd use it:
function processPrompts() {
var sheet = SpreadsheetApp.getActiveSheet();
var apiKey = "YOUR_OPENROUTER_API_KEY"; // Replace with your actual key
var model = "openai/gpt-4o"; // Or any other model
var lastRow = sheet.getLastRow();
for (var i = 2; i <= lastRow; i++) {
var prompt = sheet.getRange(i, 1).getValue(); // Column A
var existing = sheet.getRange(i, 2).getValue(); // Column B
// Skip if prompt is empty or output already exists
if (!prompt || existing) continue;
var output = sendToOpenRouter(prompt, apiKey, model);
sheet.getRange(i, 2).setValue(output);
}
}
You'd run this as a Google Apps Script, and it would process each row one by one.
Error Handling (Important!)
In production, you'll want error handling. API calls can fail, rate limits happen, and models sometimes return empty responses. Here's a basic wrapper:
function sendToOpenRouter(prompt, apiKey, model) {
var endpoint = 'https://openrouter.ai/api/v1/chat/completions';
var payload = {
model: model,
messages: [
{ role: 'user', content: prompt }
],
max_tokens: 1000,
temperature: 0.7
};
var options = {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload),
headers: {
'Authorization': 'Bearer ' + apiKey
},
muteHttpExceptions: true
};
try {
var response = UrlFetchApp.fetch(endpoint, options);
var status = response.getResponseCode();
if (status !== 200) {
return "Error: API returned status " + status;
}
var json = JSON.parse(response.getContentText());
if (json.error) {
return "Error: " + json.error.message;
}
return json.choices[0].message.content || "Empty response";
} catch (e) {
return "Error: " + e.toString();
}
}
Going Beyond the Basics
Now, the script I showed you above works great for simple use cases. But when I was building this for my own projects, I needed more:
- Processing multiple prompt/output field pairs simultaneously
- Configurable temperature and token limits
- System prompts for consistent tone
- Web search integration (yes, OpenRouter supports this!)
- Citation removal for cleaner outputs
- Smart error handling (continue vs. stop on errors)
So I built a production-ready script that handles all of this through a clean configuration interface. If you're interested in a plug-and-play solution that just works, check it out here. It's saved me hours of manual work.
🎉 Learn more about the script here
Tips I've Learned
1. Start with a Test Range: Instead of processing your entire sheet, test with a small range first. Much safer for testing.
2. Check for Existing Outputs: Always check if an output field already has content before making an API call. This prevents duplicate charges:
var existingOutput = sheet.getRange(i, 2).getValue();
if (existingOutput) continue; // Skip if already processed
3. Monitor Your Costs: OpenRouter shows you real-time costs at openrouter.ai/activity. Keep an eye on it, especially with premium models like GPT-4.
4. Temperature Matters: For factual tasks, use 0.1-0.3. For creative writing, go 0.7-0.9. This makes a bigger difference than you'd think.
5. Use a Menu for Easy Access: Add this to create a custom menu in your sheet:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('AI Tools')
.addItem('Process Prompts', 'processPrompts')
.addToUi();
}
Final Thoughts
Connecting OpenRouter to Google Sheets opens up a ton of possibilities. Whether you're generating product descriptions, analyzing customer feedback, or creating content at scale, this combination is powerful.
The basic script I shared will get you started, but if you need something more robust without the development headache, feel free to grab my production script. It's what I use daily, and it handles all the edge cases I ran into building this.