This is such a strange issue and there seems to be no documentation of it anywhere online.
Whenever I try to execute a script that requires authorization to access a
Make sure that you are using the right scope for this. To retrieve the information about a specific reporting job that has been scheduled for a channel or content owner, you must use the following authorization scopes:
https://www.googleapis.com/auth/yt-analytics.readonly
https://www.googleapis.com/auth/yt-analytics-monetary.readonly
Check this link for more information.
There is a related issue ticket which Google have marked as 'Wont't fix' which describes your problem:
If you are trying to use the YouTube API to get data about a YouTube Channel that you manage using the Google+ association system, it will get you stuck in an infinite loop. Google+ pages can “own” a YouTube channel, and the authorization will not work when trying to use one of those channels
Google do have a suggested workaround:
use the OAuth2 library to authorize access to the G+ page, and then use UrlFetchApp instead of the YouTube Advanced service to make requests to the API
As this is a problem I've also encountered I've published a detailed tutorial that uses the YouTube Data API. As the code you require also needs access via to the YouTube Analytics API there is some additional setup required detailed below and referencing the part in the tutorial:
1MWD64g7dq_ZhlN8HU_O6BRu5xNwywhp8V76utKowZEtcirEgO3t_JFFL
(Part 1.4)Add additional scopes to getYouTubeService()
for yt-analytics-monetary.readonly
and yt-analytics.readonly
(Part 2.2)
// Set the scope and additional Google-specific parameters.
.setScope(["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl",
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/youtubepartner",
"https://www.googleapis.com/auth/youtubepartner-channel-audit",
"https://www.googleapis.com/auth/yt-analytics-monetary.readonly",
"https://www.googleapis.com/auth/yt-analytics.readonly"])
Enabling the YouTube Analytics API as well as the YouTube Data API (Part 3.4)
There is also some minor modification in your code sample as to enable the library autocomplete e.g. YouTube.Channels.list()
becomes YouTube.channelsList()
and YouTubeAnalytics.Reports.query()
becomes YouTubeAnalytics.reportsQuery()
All these changes have been included in this example sheet. You'll still need to do all the setup of the console project outlined in the tutorial and in the auth.gs
sheet (I've modified the example to run in @OnlyCurrentDoc
to avoid app verification).
Note: when you run logRedirectUri()
you need to authenticate with your Google Drive account and when copy the authentication url in a new browser tab select the YouTube account you want data for.