How to Pull Google Search Results into Google Sheets (Apps Script)
A Sheets formula that searches Google on every recalculation burns API calls fast. Build a menu for keyword lists, a cached =JUSTSERP_RANK() formula and a top-10 dump with Apps Script, and learn the 30 second limit.
A custom function that runs a live Google search every time Sheets recalculates it will quietly burn through your API calls. Sheets recalculates more often than you would guess: when the file opens, when a referenced cell changes, when someone copies the formula down a column. I'll show you how I wire JustSERP into Apps Script so a menu handles whole keyword lists, a cached =JUSTSERP_RANK(keyword, domain) formula handles the odd single cell, and nothing re-runs by accident.

What you need
- A Google Sheet you can edit, and access to Extensions > Apps Script.
- A JustSERP API key. Sign up and copy the key from your dashboard.
Never paste the key into a cell or into the code, because anyone with access to the sheet could read it. Store it as a script property instead. In the Apps Script editor, open Project Settings (the gear icon), scroll to Script Properties, click Add script property, name it JUSTSERP_API_KEY and paste your key as the value. Apps Script runs on Google's servers, so the key never reaches a visitor's browser.
What happens when a cell asks for a ranking
Apps Script's UrlFetchApp service sends the HTTP request. You post a keyword to https://api.justserp.com/v1/search with your key in the X-API-Key header, and JustSERP returns the Google results as JSON. Your script then writes the parts you care about into cells.

Two details about the results are worth knowing before you build anything. We always ask Google for unfiltered, non-personalised results, so you get the full list without the "similar results omitted" trimming and without anyone's search history leaking in. And every position in the response restarts at 1 on each page, which is fine here because the sheet only reads page 1.
Speed is the other half. Most requests come back in 2 to 4 seconds. A hard query can take far longer, because we retry failed fetches for you before giving up, and that retrying can run past a minute. Most HTTP clients let you set a 90 second timeout for this reason. Apps Script does not: UrlFetchApp.fetch() has no per-request timeout option, so the platform decides how long it waits. I'll point out below where that matters.
Build it step by step
The pieces below build on each other, so follow them in order. You can use a formula for a few cells or a menu for whole lists, and the table shows which suits which job.

Step 1: the shared helpers
Open Extensions > Apps Script, delete the empty myFunction and paste this at the top. It holds everything the other pieces reuse.
const API_URL = 'https://api.justserp.com/v1/search';
const BATCH_SIZE = 10; // keep at or below your plan's concurrency
function getKey_() {
const key = PropertiesService.getScriptProperties().getProperty('JUSTSERP_API_KEY');
if (!key) throw new Error('Add JUSTSERP_API_KEY under Project Settings > Script Properties');
return key;
}
// Note: UrlFetchApp has no per-request timeout option, so none is set here.
function buildRequest_(keyword, extra) {
return {
url: API_URL,
method: 'post',
contentType: 'application/json',
headers: { 'X-API-Key': getKey_() },
payload: JSON.stringify(Object.assign({ keyword: String(keyword).trim() }, extra || {})),
muteHttpExceptions: true, // let us read the error body instead of throwing
};
}
function search_(keyword, extra) {
const response = UrlFetchApp.fetch(API_URL, buildRequest_(keyword, extra));
if (response.getResponseCode() !== 200) {
throw new Error(response.getResponseCode() + ': ' + response.getContentText());
}
return JSON.parse(response.getContentText());
}
function normalizeDomain_(domain) {
return String(domain).trim().toLowerCase().replace(/^https?:\/\//, '').replace(/^www\./, '').replace(/\/.*$/, '');
}
// Returns the first organic result whose host is the domain or one of its subdomains.
function findHit_(results, domain) {
const wanted = normalizeDomain_(domain);
for (const item of results || []) {
const match = /^https?:\/\/([^\/?#]+)/i.exec(item.link || '');
if (!match) continue;
const host = match[1].toLowerCase().replace(/^www\./, '');
if (host === wanted || host.endsWith('.' + wanted)) return item;
}
return null;
}
muteHttpExceptions matters: without it, UrlFetchApp throws on any non-200 answer and you lose the status code and message.
Step 2: a custom menu that checks a whole column
Create a sheet tab named Ranks. Put keyword in column A and the domain you want to find in column B, starting at row 2. The script fills column C with the rank, D with the ranking URL and E with the check time. Add this to the same script file:
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('JustSERP')
.addItem('Check ranks (Ranks sheet)', 'checkRanks')
.addItem('Top 10 for selected keyword', 'fetchTop10')
.addToUi();
}
function checkRanks() {
const sheet = SpreadsheetApp.getActive().getSheetByName('Ranks');
const lastRow = sheet.getLastRow();
if (lastRow < 2) return;
const rows = sheet.getRange(2, 1, lastRow - 1, 2).getValues();
const out = rows.map(() => ['', '', '']);
const todo = [];
rows.forEach((row, i) => {
if (String(row[0]).trim() && String(row[1]).trim()) todo.push(i);
});
// fetchAll sends a batch of requests in parallel.
for (let start = 0; start < todo.length; start += BATCH_SIZE) {
const idx = todo.slice(start, start + BATCH_SIZE);
const responses = UrlFetchApp.fetchAll(idx.map((i) => buildRequest_(rows[i][0])));
responses.forEach((response, k) => {
out[idx[k]] = rowResult_(response, rows[idx[k]][1]);
});
}
sheet.getRange(2, 3, out.length, 3).setValues(out);
}
function rowResult_(response, domain) {
const now = new Date();
if (response.getResponseCode() !== 200) return ['error ' + response.getResponseCode(), '', now];
const data = JSON.parse(response.getContentText());
const hit = findHit_(data.organic_results, domain);
return hit ? [hit.position, hit.link, now] : ['not on page 1', '', now];
}
Reload the sheet and a JustSERP menu appears. The first time you run an item, Google asks you to authorize the script. That is expected, because the script needs permission to call an external service and edit the spreadsheet. fetchAll sends ten requests at once, which matches the 10 concurrent requests on the Free and Personal plans. Raise BATCH_SIZE only if your plan allows more (25 on Business, 50 on Enterprise).
Menu scripts get a much longer runtime than custom functions (about 6 minutes for most accounts), so a batch that includes one slow keyword still finishes. That is the main reason I use the menu for anything longer than a handful of rows.
Step 3: dump the top 10 into a sheet
Sometimes you want to see the page, not just a rank. This menu item reads the keyword in the selected cell and writes every organic result to a Results tab:
function fetchTop10() {
const ss = SpreadsheetApp.getActive();
const keyword = String(ss.getActiveCell().getValue()).trim();
if (!keyword) {
SpreadsheetApp.getUi().alert('Select a cell that contains a keyword first.');
return;
}
const data = search_(keyword);
const rows = (data.organic_results || []).map((r) => [r.position, r.title, r.link, r.description]);
const sheet = ss.getSheetByName('Results') || ss.insertSheet('Results');
sheet.clear();
sheet.getRange(1, 1, 1, 4).setValues([['Position', 'Title', 'URL', 'Description']]);
if (rows.length) sheet.getRange(2, 1, rows.length, 4).setValues(rows);
ss.setActiveSheet(sheet);
}
Because it passes keyword only, you get United States and English by default. Add country, language, location or device to the second argument of search_() to change that, for example search_(keyword, { country: 'United Kingdom', language: 'English' }). Country and language take full English names, not codes. If you write UK or de, the API does not complain: it quietly falls back to United States and English, and the call still counts. So when a result looks wrong, open the meta.googleURL field in the response and check which Google domain was used.
For a city-level view, add a location in Google's City,Region,Country form, for example search_(keyword, { location: 'Austin,Texas,United States' }). Our local SEO guide covers how that value is checked, or rather not checked.
Step 4: a custom function with caching
A custom function lets you type =JUSTSERP_RANK(A2, "example.com") into any cell. Because Sheets re-runs formulas often, every run would cost an API call. So the function stores each answer in Apps Script's CacheService first:
function hash_(text) {
const bytes = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, text);
return Utilities.base64EncodeWebSafe(bytes);
}
/**
* Google rank of a domain for a keyword (page 1 only).
* @param {string} keyword The search term.
* @param {string} domain The domain to look for, e.g. example.com.
* @param {string} location Optional city, e.g. "Austin,Texas,United States".
* @return {number|string} The position, or "not on page 1".
* @customfunction
*/
function JUSTSERP_RANK(keyword, domain, location) {
keyword = String(keyword || '').trim();
if (!keyword || !domain) return '';
const cache = CacheService.getScriptCache();
const cacheKey = 'rank_' + hash_([keyword.toLowerCase(), normalizeDomain_(domain), location || ''].join('|'));
const cached = cache.get(cacheKey);
if (cached !== null) return cached === 'none' ? 'not on page 1' : Number(cached);
const data = search_(keyword, location ? { location: String(location) } : {});
const hit = findHit_(data.organic_results, domain);
cache.put(cacheKey, hit ? String(hit.position) : 'none', 21600); // 6 hours, the maximum
return hit ? hit.position : 'not on page 1';
}
The @customfunction tag gives you autocomplete and help text in the formula bar. Cache keys are limited in length, so the function hashes the inputs into a short key. Since position 1 on page 1 is rank 1, the position the API returns is already the absolute rank here. If you ever extend this to page 2, remember the absolute rank is (page - 1) * 10 + position.
Custom function limits to know
- 30 seconds per call. A custom function that runs longer fails. One search usually takes 2 to 4 seconds, so most calls fit. A hard query that we retry behind the scenes can run past 30 seconds, and then the cell shows an error. The request may still be counted on our side, because a call your client abandons is not refunded. Since the error is never cached, the next recalculation tries again and can cost another call.
- No timeout control. You cannot raise or lower the wait, because
UrlFetchApphas no timeout option. This is another reason to run lists from the menu, where you can at least read the status code of each response. - Cells only, no side effects. A custom function returns a value to its own cell. It cannot write elsewhere in the sheet, which is why the batch job is a menu item.
- Many formulas at once is risky. Filling 500 rows with
=JUSTSERP_RANK()starts hundreds of runs at the same time and some will fail or show an error. Use formulas for a handful of cells and the menu for lists. - It can only read a limited set of services. It cannot show dialogs or open other files, and it needs the script to be authorized once (run any menu item to do that).
- The cache expires. After six hours the next recalculation makes a fresh API call, so treat formula results as a snapshot.
What each error status means for your call count
When a call fails, the status tells you why, and it also tells you whether you were charged. A 200 uses one call. A 400 means a bad parameter, a 500 means Google could not be fetched even after our retries, and neither is charged. A 401 means a missing or wrong key and a 429 means no calls left on your plan; neither counts against you either. In the menu job, failures show as error 429 in the rank column instead of stopping the whole run, so you can fix the cause and re-run only what failed. The custom function throws before it reaches cache.put, so a bad answer is never stored.
Habits that keep the sheet cheap
- Keep the key in Script Properties, never in a cell, so sharing the sheet does not share the key.
- Use the menu for lists and formulas for single cells. It is faster, cheaper and avoids simultaneous-execution errors.
- Log history. Add a second tab and use
appendRowto write a dated rank each time you run, then chart it. - Schedule it. In the Apps Script editor, open Triggers and add a time-driven trigger for
checkRanksto refresh ranks every morning. - Default optional blocks with
|| []. Google does not show every block on every page.
Next steps
You now have live Google rankings inside Sheets. Create a free account for 2,000 free requests, no credit card needed, or see the pricing when you are ready to scale. Want the same thing outside Sheets? Read the JavaScript guide or the Python guide.