Skip to content

Commit

Permalink
Add JS sample for calling YT Analytics API (v2)
Browse files Browse the repository at this point in the history
  • Loading branch information
AndyDiamondstein committed Apr 26, 2018
1 parent 53a12c0 commit cdf1f87
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions javascript/yt_analytics_v2.html
@@ -0,0 +1,35 @@
<script src="https://apis.google.com/js/api.js"></script>
<script>
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
return gapi.client.load("https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtubeAnalytics.reports.query({
"ids": "channel==MINE",
"startDate": "2017-01-01",
"endDate": "2017-12-31",
"metrics": "views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,subscribersGained",
"dimensions": "day",
"sort": "day"
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

1 comment on commit cdf1f87

@km5464x
Copy link

@km5464x km5464x commented on cdf1f87 Mar 3, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

like it

did you manage to get the code working?

Please sign in to comment.