Last active
September 20, 2022 08:25
-
-
Save wuriyanto48/69838954ba0040aed29ecbc8360fc67f to your computer and use it in GitHub Desktop.
Nodejs: Fetch Google Analytic data with googleapi module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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