I'm transferring my iOS code from YouTube Data API v2 to v3.
I would like to retrieve the number of items in a playlist with YouTube API v3.
With the data API v2, I could call a search query, resulting in a list of playlist items with the property "size", which represented the size of the playlist, see:
https://gdata.youtube.com/feeds/api/playlists/snippets?q=GoogleDevelopers&max-results=10&v=2&alt=jsonc
With API v3, I haven't found a way to achieve this. I tried queries, like below, not resulting in the desired output.
https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=RD0KSOMA3QBU0&key={YOUR_API_KEY}
The only way to get the number of items is running a query for each playlist, retrieving the full playlist items. This is an overkill, however, and results in a too high API usage.
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=RD0KSOMA3QBU0&key={YOUR_API_KEY}
Any help appreciated!
Thanks
thanks for that. It helped me to find a solution, which is now to call
https://www.googleapis.com/youtube/v3/playlists?part=contentDetails&id={Comma Separated ID's}&key={YOUR_API_KEY}
an use the option to make a comma separate lists of the playlists to evaluate. In the return string, I grab the "itemCount" parameter for each playlist.
Thanks
Unfortunately, there is no way to get number of items in a playlist without requesting contentDetails in the parts (which isn't supported when listing playlists).
I have use the following V3 api to get the playlist videos, and its works for me.
https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=50&playlistId=PLFPg_IUxqnZM3uua-YwStHJ1qmlQKBnh0&key={YOUR_API_KEY_HERE}
**
playlistId
**
There is no details available for "playlistId" parameter in Youtube Documentation.
but is works for getting playlist videos.
This javascript will retrieve the number 91.
That is the total number of clips (total = data.pageInfo.totalResults)
from the youtube playlist
<script>
function numberOfClips(pid){
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part : 'snippet',
maxResults : 2,
playlistId : pid,
key: 'YOUR API v.3 KEY',
fields: 'pageInfo(totalResults)'
},
function(data) {
total = data.pageInfo.totalResults;
$('#total').html('Total number of clips: ' + total);
st = JSON.stringify(data,'',2);
$('#area1').val(st);
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body onload="numberOfClips('PLE9F62B21C75C054C')">
<p id="total"></p>
<textarea id='area1' style='width:400px;height:100px;'></textarea>
PLE9F62B21C75C054C
I would not recommend to rely on neither itemsCount in Playlist-Query nor pageInfo.totalResults in Playlistitems-Query, because both values may differ from the size of the retrieved list of playlist-items
see also: https://stackoverflow.com/questions/37899490/totalresults-in-playlistitems-do-not-match-items-size
Related
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've been trying to get the view count on videos that I query through the following method:
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
channelId: 'IRRELEVANT',
order: 'date',
maxResults: '25'
});
request.execute(function(response){
YoutubeResponse(response);
});
While the documentation tells me that there's a statistics portion to every video, after the snippet I have __proto__ which I guess means there was an error somewhere? or did the API change? Essentially I need the view count of those 25 most recent videos...
I tried changing part: 'snippet' to part: 'statistics' but got back a code: -32602...
Thanks for the help,
Cheers!
EDIT: Apparently the search.list doesn't have the "statistics" but rather I need to search every video individually... The thing is, when using googles "Try It" feature (https://developers.google.com/youtube/v3/docs/videos/list#try-it) when you ask for the statistics in the "Fields" part at the bottom, it doesn't do anything... So I am VERY confused as to how the heck can I get the view counts & length of all 25 videos (if individually or all at once - preferably-)
The link you gave https://developers.google.com/youtube/v3/docs/videos/list#try-it is working for me.
To get duration and viewCount: Fill in for part: contentDetails,statistics and for id: a comma-separated-list of video-id's like: TruIq5IxuiU,-VoFbH8jTzE,RPNDXrAvAMg,gmQmYc9-zcg
This will create a request as:
GET https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=TruIq5IxuiU,-VoFbH8jTzE,RPNDXrAvAMg,gmQmYc9-zcg&key={YOUR_API_KEY}
Agree with the answer provided by #Als.
But I found a code snippet which might be more convenient for some of you:
function youtube_view_count_shortcode($params)
{
$videoID = $params['id']; // view id here
$json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?
part=statistics&id=" . $videoID . "&key=xxxxxxxxxxxxxxxxxxxxxxxx");
$jsonData = json_decode($json);
$views = $jsonData->items[0]->statistics->viewCount;
return number_format($views);
}
Replace the key value with the google api key for youtube data API and the video id with the youtube video id and Voila you get the total number of views for the youtube video.
Source: https://www.codementor.io/rajharajesuwari/how-to-get-youtube-views-count-aftojpxhj
I have tried this YouTube API v3 call from curl today:
http://www.googleapis.com/youtube/v3/videos?id=ZCJgvabihQ8&key=apiKey&part=snippet,recordingDetails
Everything else is fine, but I didn't find the recordingDetails object in the response json:
{
"kind":"youtube#videoListResponse",
"etag":"\"oLweQuB9Vh7wAB9a0AIHg_K-wsM/EuRsJ-sxI3qstP1T58S5Qnb_NIg\"",
"items":[
{
"id":"ZCJgvabihQ8",
"kind":"youtube#video",
"etag":"\"oLweQuB9Vh7wAB9a0AIHg_K-wsM/CYNTRL05S4okPzkUfE5LbrRKt9g\"",
"snippet":{
"publishedAt":"2013-01-25T13:36:19.000Z",
"channelId":"UCpVm7bg6pXKo1Pr6k5kxG9A",
"title":"Weird Nature: Pink Dolphins?",
"description":"Up to 9 feet long and weighing up to 300 pounds, pink river dolphins are the largest freshwater dolphins in the world.",
"thumbnails":{
"default":{
"url":"https://i.ytimg.com/vi/ZCJgvabihQ8/default.jpg"
},
"medium":{
"url":"https://i.ytimg.com/vi/ZCJgvabihQ8/mqdefault.jpg"
},
"high":{
"url":"https://i.ytimg.com/vi/ZCJgvabihQ8/hqdefault.jpg"
}
},
"categoryId":"24"
}
}
]
}
Is there anything I missed? Many thanks.
recordingDetails is not public for all videos, so if a video doesn't have these attributes available, nothing will be returned. By not returning anything, YouTube saves bandwidth and the response time can be faster.
Original reponse:
This looks like a legitimate bug...
recordingDetails is listed as an option on the videos resource
overview page, but not listed as a valid part in the video list method
here: https://developers.google.com/youtube/v3/docs/videos/list
Normally when you try using an invalid part you get a "400 Bad
Request" error, but recordingDetails still returns a 200 response, so
it looks like it really is supposed to be returned...
You should submit a bug report here:
https://code.google.com/p/gdata-issues/issues/entry?template=YouTube%20(Defect%20Report)
recordingDetails will only be returned for videos that explicitly have either the geolocation or the recording time set.
(Not all videos set recording time; it's a distinct piece of metadata from publication time.)
You can do a list call to retrieve a list of videos based on a location and locationRadius.
Then, with the returned list you can do a videos call including all video IDs in the id parameter of the query. You can then specify recordingDetails as "part" and it will work.
This is how Youtube does it here:
https://github.com/youtube/geo-search-tool
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;