Skip to content

Instantly share code, notes, and snippets.

@Maxim-Mazurok
Created September 24, 2020 02:06
Show Gist options
  • Save Maxim-Mazurok/84fcbe394ea289531c3ad4fa1d293cf0 to your computer and use it in GitHub Desktop.
Save Maxim-Mazurok/84fcbe394ea289531c3ad4fa1d293cf0 to your computer and use it in GitHub Desktop.
Analytics Reporting API V4 demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hello Analytics Reporting API V4</title>
<meta name="google-signin-client_id" content="CLIENT_ID" />
<meta
name="google-signin-scope"
content="https://www.googleapis.com/auth/analytics.readonly"
/>
<script src="https://apis.google.com/js/client:platform.js"></script>
</head>
<body>
<h1>Hello Analytics Reporting API V4</h1>
<!-- The Sign-in button. This will run `queryReports()` on success. -->
<p class="g-signin2" data-onsuccess="queryReports"></p>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
gapi.load('client', () => {
/** now we can use gapi.client */
gapi.client.load('analyticsreporting', 'v4', () => {
/** now we can use gapi.client.analyticsreporting */
/** don't forget to authenticate your client before sending any request to resources: */
/** declare client_id registered in Google Developers Console */
const client_id = 'CLIENT_ID';
const scope = [
/** View and manage your Google Analytics data */
'https://www.googleapis.com/auth/analytics',
/** View your Google Analytics data */
'https://www.googleapis.com/auth/analytics.readonly',
];
const immediate = false;
gapi.auth.authorize({client_id, scope, immediate}, authResult => {
if (authResult && !authResult.error) {
/** handle successful authorization */
// Replace with your view ID.
var VIEW_ID = 'VIEW_ID';
// Query the API and print the results to the page.
gapi.client.analyticsreporting.reports
.batchGet({
resource: {
reportRequests: [
{
viewId: VIEW_ID,
dateRanges: [
{
startDate: '7daysAgo',
endDate: 'today',
},
],
metrics: [
{
expression: 'ga:sessions',
},
],
},
],
},
})
.execute(displayResults, console.error.bind(console));
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
} else {
/** handle authorization error */
}
});
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment