Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Last active September 20, 2022 08:25
Show Gist options
  • Select an option

  • Save wuriyanto48/69838954ba0040aed29ecbc8360fc67f to your computer and use it in GitHub Desktop.

Select an option

Save wuriyanto48/69838954ba0040aed29ecbc8360fc67f to your computer and use it in GitHub Desktop.
Nodejs: Fetch Google Analytic data with googleapi module
const { google } = require('googleapis');
const fs = require('fs');
const analyticsreporting = google.analyticsreporting('v4');
const setAuth = () => {
// Obtain user credentials to use for the request
const auth = new google.auth.GoogleAuth({
keyFile: 'your_service_account.json',
scopes: ['https://www.googleapis.com/auth/analytics']
});
google.options({auth});
};
// https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet
async function batchGet() {
// set auth
setAuth();
const res = await analyticsreporting.reports.batchGet({
requestBody: {
reportRequests: [
{
viewId: '210916xxx',
dateRanges: [
{
startDate: '2022-02-01',
endDate: '2022-02-22',
},
{
startDate: '14daysAgo',
endDate: '7daysAgo',
},
],
metrics: [
{
expression: 'ga:sessions',
},
],
dimensions: [
{
name:"ga:browser"
},
{
name:"ga:clientId"
}
],
},
],
},
});
return res.data;
}
// https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/userActivity/search
async function userSearch() {
// set auth
setAuth();
const res = await analyticsreporting.userActivity.search({
requestBody: {
viewId: '210916xxx',
user: {
'type': 'CLIENT_ID',
'userId': '409760102.1643249907'
},
dateRange: {
startDate: '2022-02-01',
endDate: '2022-02-22',
}
}
});
return res.data;
}
batchGet().then(data => {
const jsonString = JSON.stringify(data);
fs.writeFile("output.json", jsonString, 'utf8', function (err) {
if (err) {
console.log("An error occured while writing JSON Object to File.");
return console.log(err);
}
console.log("JSON file has been saved.");
});
})
.catch(e => console.log('error: ', e));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment