I'm trying to use the YouTube Analytics and Reporting API with Google Apps Script to populate a Google Sheet with analytics data from YouTube brand accounts that I own and manage.
As a preface, I have tried this on YouTube channels that I own and channels that I manage and nothing has worked. I have also taken a look at all of the Stack Overflow questions & responses related to this for the past few days and nothing has worked. Believe me when I say I have tried everything. I do not believe the code or the way I set things up is the issue; I believe it has to do with Google or the YouTube API itself.
Here are the steps I have taken:
Enable the YouTube Analytics API and YouTube Data API in Google Apps Script. (The YouTube Reporting API is nowhere to be found which may be the issue...)
Enable the same APIs in Google Developer Console (The YouTube Reporting API is available there)
Set up a Client ID & Secret and linked my project to the Apps Script
Verified that my code indeed works by inputting the same exact parameters (metrics, dimensions, etc.) in the YouTube Analytics and Reporting API Explorer in Google Developer Console. When I do this, the explorer does indeed export the right information. However, in Google Apps Script, it does not work at all.
Due to the fact that the code works in the Explorer, but not in Google Apps Script, I believe that there's something simple that I'm doing wrong, or it's an error on the Google side. I'm hoping that there's a way around this or a fix, because I'd really like to get the data from my YouTube channels into Google Sheets.
Google Apps Script code (shortened for simplicity. The "key" property may not be necessary, but it doesn't work without it either).
function myFunction() {
var metrics = [
'averageViewDuration'
];
var oneMonthInMillis = 1000 * 60 * 60 * 24 * 30;
var today = new Date();
var lastMonth = new Date(today.getTime() - oneMonthInMillis);
var report = YouTubeAnalytics.Reports.query({
ids: 'channel==MINE',
startDate: formatDateString(lastMonth),
endDate: formatDateString(today),
metrics: metrics.join(','),
dimensions: 'day',
sort: 'day',
includeHistoricalChannelData: false,
key: "AIzaSyAcVb-hriIydRs8iVqFZ6ZoyL8En3qLcnc",
});
Logger.log(report);
}
When I run the code, there is zero output to the logger. I expect there to be something there.
As a reminder, this happens when I select any account besides my core account. When I select the core account attached to the account (that does not have a YouTube channel), it does output this:
"[19-10-30 17:58:19:251 PDT] {columnHeaders=[{columnType=DIMENSION, dataType=STRING, name=day}, {columnType=METRIC, dataType=INTEGER, name=averageViewDuration}], kind=youtubeAnalytics#resultTable, rows=[[2019-09-30, 0], [2019-10-01, 0], [2019-10-02, 0], [2019-10-03, 0], [2019-10-04, 0], [2019-10-05, 0], [2019-10-06, 0], [2019-10-07, 0], [2019-10-08, 0]...]]}"
There's no reason that it shouldn't be working. What do you think is the issue?