Skip to content

Commit cdf1f87

Browse files
Add JS sample for calling YT Analytics API (v2)
1 parent 53a12c0 commit cdf1f87

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

javascript/yt_analytics_v2.html

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<script src="https://apis.google.com/js/api.js"></script>
2+
<script>
3+
function authenticate() {
4+
return gapi.auth2.getAuthInstance()
5+
.signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})
6+
.then(function() { console.log("Sign-in successful"); },
7+
function(err) { console.error("Error signing in", err); });
8+
}
9+
function loadClient() {
10+
return gapi.client.load("https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2")
11+
.then(function() { console.log("GAPI client loaded for API"); },
12+
function(err) { console.error("Error loading GAPI client for API", err); });
13+
}
14+
// Make sure the client is loaded and sign-in is complete before calling this method.
15+
function execute() {
16+
return gapi.client.youtubeAnalytics.reports.query({
17+
"ids": "channel==MINE",
18+
"startDate": "2017-01-01",
19+
"endDate": "2017-12-31",
20+
"metrics": "views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,subscribersGained",
21+
"dimensions": "day",
22+
"sort": "day"
23+
})
24+
.then(function(response) {
25+
// Handle the results here (response.result has the parsed body).
26+
console.log("Response", response);
27+
},
28+
function(err) { console.error("Execute error", err); });
29+
}
30+
gapi.load("client:auth2", function() {
31+
gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});
32+
});
33+
</script>
34+
<button onclick="authenticate().then(loadClient)">authorize and load</button>
35+
<button onclick="execute()">execute</button>

0 commit comments

Comments
 (0)