I am running the following query with Youtube Analytics API
now = datetime.datetime.now()
start_date = (now - datetime.timedelta(days=4)).strftime('%Y-%m-%d')
end_date = (now - datetime.timedelta(days=3)).strftime('%Y-%m-%d')
args = {
'metrics': 'views,estimatedMinutesWatched',
'dimensions': 'subscribedStatus',
'ids': 'channel==<my_channel_id>',
'startDate': start_date,
'endDate': end_date
}
analytics_query_response = youtube.reports().query(**args).execute()
I am using youtube analytics api version 2 and changed the end_date parameter to endDate and start_date to startDate and I am getting the following response
{u'kind': u'youtubeAnalytics#resultTable', u'rows': [], u'columnHeaders': [{u'dataType': u'STRING', u'columnType': u'DIMENSION', u'name': u'subscribedStatus'}, {u'dataType': u'INTEGER', u'columnType': u'METRIC', u'name': u'views'}, {u'dataType': u'INTEGER', u'columnType': u'METRIC', u'name': u'estimatedMinutesWatched'}]}
I get the 'rows' in response but it's empty. When I try with the same parameters in Youtube API Explorer, it gives me the result for 'rows'.
What I am doing wrong here?
First, you need to add the scope: "Youtube".
Then, try to delete the file: "Google.Apis.Auth.OAuth2.Responses.TokenResponse-..." located in my case at: ".\users\admin\appdata\roamming\YouTubeAnaltycis.Auth.Store"
It´s works for me.
Best regards.
Related
I have the Academic Research access to Twitter's API and have been using Tweepy to access the API. My problem is I cannot retrieve the tweets from older tweets
This is the code attempting to retrieve the tweets using the conversation_id, from 2014
# https://twitter.com/NintendoAmerica/status/535462600294035456
start_time = '2014-11-01T00:00:00Z'
end_time = '2014-12-12T00:00:00Z'
tweets = client.search_all_tweets(query = 'conversation_id:535462600294035456', max_results = 500, start_time=start_time, end_time=end_time)
and the output is:
Response(data=[<Tweet id=535465221679489024 text='#NintendoAmerica #Pokemon [this was a link I had to remove]'>], includes={}, errors=[], meta={'newest_id': '535465221679489024', 'oldest_id': '535465221679489024', 'result_count': 1})
which is only one seemingly random tweet amongst many.
However, when I tried running the same code on a more recent tweet, it retrieved all the tweets. I do not have to specify a start/end time because it's a tweet from the past 30 days.
# https://twitter.com/380kmh/status/1545477360916373504
tweets = client.search_all_tweets(query = 'conversation_id:1545477360916373504', max_results = 500)
the output was complete (shortened, I removed the tweets):
Response(data=[...], meta={'newest_id': '1546465585093087235', 'oldest_id': '1545477768229670912', 'result_count': 18})
I followed Tweepy's documentation here, using Client.search_all_tweets:
https://docs.tweepy.org/en/stable/client.html#tweepy.Client.search_all_tweets
I also tried using Postman to retrieve the tweets but it came out empty, even though I followed the documentation here:
https://developer.twitter.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-all#tab0
Query: https://api.twitter.com/2/tweets/search/all?query=conversation_id%3A537923834557771776&start_time=2014-11-01T00:00:00.000Z&end_time=2014-12-18T00:00:00.000Z&tweet.fields=in_reply_to_user_id,text
Output:
{
"meta": {
"result_count": 0
}
}
What am I doing wrong?
We got to build our own reporting database for our Youtube channel to measure the channel and video performance.
To support this, we implemented an ETL job to extract using Youtube Analytics API and used below python code to get the data.
def GetAnalyticsData(extractDate,accessToken, channelId):
channelId = 'channel%3D%3D{0}'.format(channelId)
headers = {'Authorization': 'Bearer {}'.format(accessToken),
'accept': 'application/json'}
url = 'https://youtubeanalytics.googleapis.com/v2/reports?dimensions={dimensions}&endDate={enddate}&ids={ids}&maxResults={maxresults}&metrics={metrics}&startDate={startdate}&alt={alt}&sort={sort}'.format(
dimensions='video',
ids=channelId,
enddate= extractDate,
startdate=extractDate,
metrics = 'views%2Ccomments%2Clikes%2Cdislikes%2Cshares%2CestimatedMinutesWatched%2CsubscribersGained%2CsubscribersLost%2CannotationClicks%2CannotationClickThroughRate%2CaverageViewDuration%2CaverageViewPercentage%2CannotationCloseRate%2CannotationImpressions%2CannotationClickableImpressions%2CannotationClosableImpressions%2CannotationCloses',
maxresults = 200,
alt ='json',
sort='-views'
)
return requests.get(url,headers=headers)
We hit this API everyday and get all the video metric and sorted by views in descending order.
This solved our need partially and it returns only 200 videos, if we specify maxResults more than 200, its return 400 error code.
The challenge is, how to get all videos for the given date and given channel?
Thanks in advance.
Regards,
Guna
I am not keen on YouTube analytics API, but it seems that you are looking for startIndex.
startIndex
integer
The 1-based index of the first entity to retrieve. (The default value is 1.) Use this parameter as a pagination mechanism along with the max-results parameter.
So I am trying to grab 10 latest videos from user uploads.
Now the only problem is that the only date visible in the playlistitems request is publishedAt which is the date when the video was uploaded
- not the date of when it was made public, which makes a huge difference.
I noticed that I can grab the correct date via the video request, but it just does not seem to be the best place to do it.
Let me show you an example of what I am dealing with.
Let's take Maroon5 channel.
forUserName: Maroon5VEVO
GET https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=Maroon5VEVO&key={YOUR_API_KEY}
https://developers.google.com/youtube/v3/docs/channels/list#try-it
Here is where we grab the:
uploadsId: UUN1hnUccO4FD5WfM7ithXaw
So we can query:
GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUN1hnUccO4FD5WfM7ithXaw&maxResults=50&key={YOUR_API_KEY}
https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it
and then we can have a look at some videos.
Let's grab the latest one. For me it is this one:
"title": "Maroon 5 - This Summer's Gonna Hurt Like A ... (Explicit)",
"videoId": "Wa64gOwuIyE"
And most importantly :
"publishedAt": "2015-06-01T17:41:58.000Z",
Now let's grab more details of this video, by running this query:
GET https://www.googleapis.com/youtube/v3/videos?part=snippet&id=Wa64gOwuIyE&key={YOUR_API_KEY}
https://developers.google.com/youtube/v3/docs/videos/list#try-it
Here we get more detailed view with a date that is ... different !
"publishedAt": "2015-06-01T20:00:01.000Z",
That means that the publishedAt date in playlists is actually the date of the upload - not when the video was made public.
In our list of 10 latest items we want the LATEST published videos , and not latest uploaded vids.
If you know a way how to approach it , please share.
Here is my snippet for now (working with a wrong publishedAt date)
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part : 'snippet',
maxResults : 10,
playlistId : UPLOADS_PID,
key: YOUR_API_KEY},
function(data) {
$.each( data.items, function(i, item ) {
(...)
});
}
);
I believe you can use /search endpoint. As you want to grab 10 latest videos from user uploads, you can use channel id instead of playlist id.
Request:
GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANNEL_ID}&maxResults=10&order=date&type=video&key={YOUR_API_KEY}
(I wrote "Hello", but it gets removed.)
I'm using the youtube api from an android application.
I was getting the channelId from a "channel" search by looking at id.channelid. Now it seems to have been changed to snippet.channelid.
But the field value is always "UC". ???
The code:
YouTube.Search.List search = youtube.search().list("id,snippet");
search.setKey("my key");
search.setQ("whatever channel name");
search.setType("channel");
search.setFields("items(snippet(channelId))");
search.setMaxResults((long)1);
SearchListResponse searchResponseC = search.execute();
List<SearchResult> searchResultListC = searchResponseC.getItems();
String channelid = ((SearchResult)searchResultListC.get(0)).getSnippet().getChannelId();
Now channelid value is "UC".
Also, I'm not sure if the line search.setType("channel"); has any effect.
Help, please.
Its a known issue with the V3 api this week.
https://code.google.com/p/gdata-issues/issues/detail?id=4971
I want to get the total amount of views (all videos) from a channel on youtube using the Youtube API in PHP. I didn't found any method to do that. Does anyone have en idea ? Thanks in advance for your help.
You can use the new YouTube Analytics API
https://developers.google.com/youtube/analytics/v1/available_reports
you can modify the code of the sample application to call the api in the client side:
https://developers.google.com/youtube/analytics/v1/sample-application
and do something like this to get the number of views per day:
var request = gapi.client.youtubeAnalytics.reports.query({
// Convert dates to YYYY-MM-DD strings for start-date and end-date parameters.
'start-date': formatDateString(lastWeek),
'end-date': formatDateString(today),
// Identify channel for which you're retrieving data.
ids: 'channel==' + channelId,
dimensions: 'day',
metrics: 'views'
});
This is the code (don't forget to rename yourUserName with your YouTube username):
$xdoc = new DomDocument;
$xdoc->Load('http://gdata.youtube.com/feeds/api/users/yourUserName');
$ytstat = $xdoc->getElementsByTagName('statistics')->item(0);
$total_views = $ytstat->getAttribute(totalUploadViews);
echo $total_views;