Search code examples
google-apps-scriptyoutube-apigoogle-appsyoutube-analytics-apiyoutube-analytics

YouTube API - Video as a Dimension is not working, because maxResults does not work


I am trying to use Google AppsScript to sort all my YouTube videos in a sheet by the amount of revenue they earned in the last month. However I keep getting an error when I set the 'dimensions' to video:

Error:{  
   "error":{  
      "errors":[  
         {  
            "domain":"global",
            "reason":"badRequest",
            "message":"The query is not supported. Check the documentation at https://developers.google.com/youtube/analytics/v1/available_reports for a list of supported queries."
         }
      ],
      "code":400,
      "message":"The query is not supported. Check the documentation at https://developers.google.com/youtube/analytics/v1/available_reports for a list of supported queries."
   }
}(line 53,
file "Code",
project "YoutubeAnalytics")

Here is my code:

var analyticsResponse = YouTubeAnalytics.reportsQuery('channel==' + channelId,
    oneMonthAgoFormatted,
    todayFormatted,
    'views', 

{
    dimensions:
    'video',
    maxResults:
    5,
    sort:
    '-views'
});

If I simply change 'video' to 'day' or '7DayTotals' it works as expected, as these are also example dimensions listed here: https://developers.google.com/youtube/analytics/v1/dimsmets/dims

(Interestingly, and a possible hint, the 'gender' dimension does not work either and throws the same error as above')

I suspect, from looking at similar questions on StackOverflow, that the issue might be that maxResults must be declared, and for some reason mine isn't working. Even when I set the dimensions to 'day' and get an error-free report, the maxResults are never limited to the integer I assign it. It will instead give 30 results since I have a 30 day range and am giving it a 'day' dimension.

Any help would be greatly appreciated, thanks.


Solution

  • Okay. I was correct in assuming that they didn't like me using video as a dimension because maxResults was not working.

    The correct way to format maxResults inside of AppsScript is: 'max-results': '5'

    So the completed, working, line of code is:

        var analyticsResponse = YouTubeAnalytics.reportsQuery('channel==' + channelId,
        oneMonthAgoFormatted,
        todayFormatted,
        'views', 
    
    {
        dimensions: 'video',
        'max-results': '5',
        sort: '-views'
    });