searchConsoleQuery(siteUrl, opts) queries the Search Console search-analytics API with ScriptApp.getOAuthToken() and returns row objects (query, clicks, impressions, ctr, position, plus any other dimensions you asked for) ready for Append an Object as a Sheet Row. {startDate}, {endDate}, {dimensions}, and {rowLimit} are optional.
When to use
- A Monday job that appends last week's clicks and top queries
- A property you already verified in Search Console
- Any script that should read search performance and not write to the site
How to use this snippet
siteUrl must be the exact property from Search Console, including the trailing slash on a URL-prefix property (https://example.com/) or the sc-domain:example.com form for a domain property.
Add the read-only scope to appsscript.json and enable the Google Search Console API in the Cloud project attached to the script:
"oauthScopes": [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/webmasters.readonly"
]
/**
* Query Search Console search analytics and return row objects for
* appendObjectAsRow. Uses ScriptApp.getOAuthToken() and the webmasters
* v3 searchAnalytics.query API. opts.dimensions defaults to ["query"],
* opts.rowLimit to 1000 (max 25000). If dates are omitted, the window is
* 28 days ending two days ago (Search Console data lags). Dates are
* yyyy-MM-dd or Date. Throws on a non-2xx response with a hint about
* the API, the readonly scope, and the exact property URL.
*
* @param {string} siteUrl
* @param {{startDate?: string|Date, endDate?: string|Date, dimensions?: string[], rowLimit?: number}} [opts]
* @return {Array<Object>}
*/
function searchConsoleQuery(siteUrl, opts) {
opts = opts || {};
var site = String(siteUrl == null ? '' : siteUrl).trim();
if (!site) throw new Error('searchConsoleQuery: siteUrl required (the exact Search Console property, e.g. https://example.com/ or sc-domain:example.com)');
function ymd_(value, label) {
if (value == null || value === '') return '';
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value.trim())) return value.trim();
var d = value instanceof Date ? value : new Date(value);
if (isNaN(d.getTime())) throw new Error('searchConsoleQuery: ' + label + ' is not a valid date');
return Utilities.formatDate(d, 'UTC', 'yyyy-MM-dd');
}
function addDaysYmd_(ymd, n) {
var p = ymd.split('-');
var cur = new Date(Date.UTC(Number(p[0]), Number(p[1]) - 1, Number(p[2]) + n));
var pad = function (x) { return (x < 10 ? '0' : '') + x; };
return cur.getUTCFullYear() + '-' + pad(cur.getUTCMonth() + 1) + '-' + pad(cur.getUTCDate());
}
var endDate = ymd_(opts.endDate, 'endDate');
var startDate = ymd_(opts.startDate, 'startDate');
if (!endDate) {
endDate = addDaysYmd_(Utilities.formatDate(new Date(), 'UTC', 'yyyy-MM-dd'), -2);
}
if (!startDate) startDate = addDaysYmd_(endDate, -27);
if (startDate > endDate) {
throw new Error('searchConsoleQuery: startDate must be on or before endDate');
}
var dimensions = opts.dimensions == null ? ['query'] : opts.dimensions;
if (Object.prototype.toString.call(dimensions) !== '[object Array]') {
throw new Error('searchConsoleQuery: dimensions must be an array of strings');
}
var rowLimit = opts.rowLimit == null ? 1000 : Number(opts.rowLimit);
if (!(rowLimit >= 1) || Math.floor(rowLimit) !== rowLimit || rowLimit > 25000) {
throw new Error('searchConsoleQuery: rowLimit must be an integer from 1 to 25000');
}
var token = ScriptApp.getOAuthToken();
var url = 'https://www.googleapis.com/webmasters/v3/sites/' +
encodeURIComponent(site) + '/searchAnalytics/query';
var payload = {
startDate: startDate,
endDate: endDate,
dimensions: dimensions,
rowLimit: rowLimit
};
var resp = UrlFetchApp.fetch(url, {
method: 'post',
contentType: 'application/json',
muteHttpExceptions: true,
headers: { Authorization: 'Bearer ' + token },
payload: JSON.stringify(payload)
});
var code = resp.getResponseCode();
var body = String(resp.getContentText() || '');
var parsed = {};
try { parsed = body ? JSON.parse(body) : {}; } catch (err) { parsed = {}; }
if (code < 200 || code >= 300) {
var msg = (parsed && parsed.error && parsed.error.message) ? parsed.error.message : body;
throw new Error(
'searchConsoleQuery: Search Console API returned ' + code +
'. Enable the Google Search Console API in the Cloud project, add the ' +
'https://www.googleapis.com/auth/webmasters.readonly scope to appsscript.json, ' +
'and use the exact property URL from Search Console. ' +
(msg ? '(' + msg + ')' : '')
);
}
var rows = (parsed && parsed.rows) || [];
var out = [];
for (var i = 0; i < rows.length; i++) {
var row = rows[i] || {};
var obj = {};
var keys = row.keys || [];
for (var d = 0; d < dimensions.length; d++) {
obj[dimensions[d]] = keys[d] == null ? '' : keys[d];
}
obj.clicks = row.clicks == null ? 0 : row.clicks;
obj.impressions = row.impressions == null ? 0 : row.impressions;
obj.ctr = row.ctr == null ? 0 : row.ctr;
obj.position = row.position == null ? 0 : row.position;
out.push(obj);
}
return out;
}
Example
function appendSearchConsole() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Search Console') ||
SpreadsheetApp.getActive().insertSheet('Search Console');
if (sheet.getLastRow() === 0) {
sheet.getRange(1, 1, 1, 5).setValues([['query', 'clicks', 'impressions', 'ctr', 'position']]);
}
var rows = searchConsoleQuery('https://bootstrapping.tools/', {
dimensions: ['query'],
rowLimit: 1000
});
rows.forEach(function (row) { appendObjectAsRow(sheet, row); });
}
Header names must match the object keys exactly, including case.
Notes
- This is a read. The token is used only to query search analytics; the helper does not change your site or property settings.
- A 403 usually means the API is not enabled, the scope is missing, or
siteUrldoes not match the verified property. - One request returns at most
rowLimitrows (the API cap is 25,000). For a longer list, narrow the dates or add a dimension.
Happy Coding!
