6

I am able to successfully make requests to Youtube Analytics API via the API Explorer. My code is attempting to use the Google PHP Client library, specifically the Google_Service_YouTubeAnalytics class. Unfortunately, there is no documentation on this class.

I am setting the ID and Assertion Credentials on the client. I'm fairly confident this is working correctly, because if I change the private key to something I know to be incorrect, I get:

{"code":400,"error":"Error refreshing the OAuth2 token, message: '{\n \"error\" : \"invalid_grant\"\n}'"}

But when I insert the correct private key, I get the following response:

{"code":400,"error":"Error calling GET https:\/\/www.googleapis.com\/youtube\/analytics\/v1\/reports?ids=channel%3D%3DCHANNEL_ID&start-date=2014-09-01&end-date=2014-09-05&metrics=views%2Cuniques: (400) Invalid query. Query did not conform to the expectations."}

It doesn't tell me what is invalid about the query (which would be incredibly helpful), so I have no idea what I could be doing incorrectly. Any help is appreciated.

Here is my code that makes the request:

$client = new \Google_Client();
$client->setApplicationName(self::APP_NAME);

// set some stuff
$client->setClientId( self::CLIENT_ID );
$client->setClientSecret( self::CLIENT_SECRET );
$client->setAssertionCredentials(new \Google_Auth_AssertionCredentials(
    self::CRED_ID,
    [
        "https://www.googleapis.com/auth/youtube.readonly",
        'https://www.googleapis.com/auth/yt-analytics.readonly'
    ],
    self::youtubeKey()
));

$youtubeService = new \Google_Service_YouTubeAnalytics($client);
$resp = $youtubeService->reports->query(
    self::CHANNEL_ID,
    '2014-09-01',
    '2014-09-05',
    'views,uniques'
);
John D.
  • 2,521
  • 3
  • 24
  • 45
  • Also, I am using the Google Analytics client library in my code, and that works fine. I'm using the code in almost the same way. Uggh. – John D. Oct 17 '14 at 17:54
  • Is your app actually sending the string "channel==CHANNEL_ID" as the value of the ids parameter, or is your modification when you pasted the error code in SO? – jlmcdonald Oct 18 '14 at 05:24
  • No, I changed that in order to hide my actual channel ID in this post. In my code, it is my channel ID value. – John D. Oct 20 '14 at 16:20
  • 1
    Post the code you're using to make the request that throws this error. Also, reading the comments on the library's source code is usually very helpful. – Vinicius Braz Pinto Nov 03 '14 at 00:48
  • 1
    Any update on this issue? I'm facing the same problem, but instead of oAuth I'm trying to use service accounts. http://stackoverflow.com/questions/26714387/youtube-analytics-api-php-invalid-query-query-did-not-conform-to-the-expectatio – G.T. Nov 03 '14 at 13:27
  • Posted the code. Still cannot get this to work. Have tried to contact Google Apps support via my org's account, they replied with "We don't provide service for that API." Thanks for the help, Google. Though to be fair, they probably don't make enough money to pay someone to support the products they make. (That was a joke) I have no idea how anyone would ever get this to work by themselves with no outside help. – John D. Nov 04 '14 at 02:01

2 Answers2

1

You are making a not supported query, it's no possible to use views & uniques with no dimensions provided. You can check it in Youtube's Analytics API Reference.

Try add it a dimension like day and it will work:

$youtubeService = new \Google_Service_YouTubeAnalytics($client);
$resp = $youtubeService->reports->query(
    self::CHANNEL_ID,
    '2014-09-01',
    '2014-09-05',
    'views,uniques',
    array('dimensions' => 'day')
);

That query will get a Response similar to:

200 OK

- Show headers -

{
 "kind": "youtubeAnalytics#resultTable",
 "columnHeaders": [
  {
   "name": "day",
   "columnType": "DIMENSION",
   "dataType": "STRING"
  },
  {
   "name": "views",
   "columnType": "METRIC",
   "dataType": "INTEGER"
  },
  {
   "name": "uniques",
   "columnType": "METRIC",
   "dataType": "INTEGER"
  }
 ],
 "rows": [
  [
   "2014-09-04",
   1250,
   621
  ],
  [
   "2014-09-05",
   1265,
   577
  ],
  [
   "2014-09-03",
   1255,
   557
  ],
  [
   "2014-09-01",
   1076,
   532
  ],
  [
   "2014-09-02",
   1182,
   570
  ]
 ]
}

Google's APIs Explorer is a very useful tool in order to test your queries.


For documentation purposes you can have a look to the source code and the classes themselves, they are very well documented and "maybe" self-explanatory.


A newer approach is to make requests to this API using oAuth 2.0 protocol for authorizing access.
Google provides an amazing resource to try all this stuff: OAuth 2.0 Playground

Basically, you need to get an access token and its refresh token to apply it when the prior expires.

$client = new \Google_Client();
$client->setApplicationName(self::APP_NAME);

// set some stuff
$client->setClientId( self::CLIENT_ID );
$client->setClientSecret( self::CLIENT_SECRET );

// Set oAuth info
$client->addScope(\Google_Service_YouTubeAnalytics::YT_ANALYTICS_READONLY);
$client->setAccessToken($accessToken);

// Check if token is expired
if ($client->isAccessTokenExpired()) {
    $client->refreshToken($refreshToken());
    $newToken = $client->getAccessToken();

    $authObj = json_decode($newToken);
    if (!is_object($authObj)) {
        throw new \Google_Auth_Exception('Error on updating oAuth tokens');
    }

    //update tokens
    //...            
}

$youtubeService = new \Google_Service_YouTubeAnalytics($client);

Hope it helps!

guillermogfer
  • 362
  • 4
  • 9
0

You need to add a Google API key

    https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel_ID&start-date=2014-09-01&end-
date=2014-10-01&metrics=views%2Cuniques&key={YOUR_API_KEY}

Also I am not sure if "%2Cuniques" => "uniques" is valid metric.

You can use Google automated tool to generate a valid link.

https://developers.google.com/youtube/analytics/v1/

SergeDirect
  • 2,019
  • 15
  • 20