Objectives: Implement a program (java or python) to retrieve data from videos that I published on my Youtube channel. This program will be launched daily (1:00 AM).
Solutions: To retrieve data Youtube, including the number of views per day, YouTube Analytics API is in my opinion the best solution. I use the Google Account Service ("GoogleCredential") to authenticate me:
static {
// Build service account credential.
try {
// Create a listener for automatic refresh OAuthAccessToken
List<CredentialRefreshListener> list = new ArrayList<CredentialRefreshListener>();
list.add(new CredentialRefreshListener() {
public void onTokenResponse(Credential credential,
TokenResponse tokenResponse) throws IOException {
System.out.println(tokenResponse.toPrettyString());
}
public void onTokenErrorResponse(Credential credential,
TokenErrorResponse tokenErrorResponse)
throws IOException {
System.err.println("Error: "
+ tokenErrorResponse.toPrettyString());
}
});
// Create a GoogleCredential for authenticate with ServiceAccount
// service
credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPES)
.setClock(Clock.SYSTEM)
.setServiceAccountPrivateKeyFromP12File(
new File("key.p12"))
.setRefreshListeners(list).build();
credential.refreshToken();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And I execute Youtube Analytics query:
YoutubeAnalytics youtubeAnalytics = new YoutubeAnalytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("Test-YouTube-Analytics/1.0").build();
// Create request
credential.refreshToken();
YoutubeAnalyticsRequest<?> request = youtubeAnalytics.reports()
.query("channel==" + channelId, "2012-10-01", "2012-12-01", "views")
.setAlt("json")
.setKey(API_KEY)
.setDimensions("month")
.setPrettyPrint(true);
System.out.println(request.buildHttpRequest().getUrl().toString());
ResultTable first = (ResultTable) request.execute();
}
But I get the following error:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 500 Internal Server Error
{
"code" : 500,
"errors" : [ {
"domain" : "global",
"message" : "Unknown error occurred on the server.",
"reason" : "internalError"
} ],
"message" : "Unknown error occurred on the server."
}
Thanks for your insight!