Youtube API 3 get latest videos - youtube-api

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}

Related

YouTube IFrame Player API getVideoData is removed: how to get title?

On November 13th, I got a call from a customer reporting that the YouTube player didn't work anymore. After a quick look in the dev tool, I found that there was an error:
Uncaught TypeError: a.getVideoData is not a function
Looking into what the player object was containing, I learned that there's no function getVideoData anymore.
The function getVideoData provided a way to get the video title. Now, how can I get the title?
Is there any article from Google about this change?
To get a video's title, you can query the YouTube Data API v3:
GET https://www.googleapis.com/youtube/v3/videos
?part=snippet
&id=VIDEO_ID
&key=YOUR_API_KEY
For that you need to sign up on the Google Cloud Console and create an API key (it's free). You can restrict the API key to only be used from your website, that way you can safely make it public in your JS source code/html code without others being able to make queries on your behalf. Make sure to enable the YouTube Data API v3 in the console as well, otherwise your queries will return errors.
The above query will return a JSON representation of the information on the video that you are interested in (the snippet part). Say you parse the JSON into an object called result. Then you can get the video title via
result.items[0].snippet.title
getVideoData() seems to be back (Dec, 2017). So, try again !
As of today (October 1st, 2020), I am retrieving the title of the video from within YouTube's API object:
// Assigning YouTube's ID to your ID variable
const playerID = "xxxxxxx";
// Creating an object for the video using YouTube's API.
const yPlayer = new YT.Player(playerID, {
events: {
'onReady': onPlayerReady(),
'onStateChange': onPlayerStateChange()
}
});
function onPlayerReady() {
}
function onPlayerStateChange() {
// Title retrieved here
let videoTitle = yPlayer.j.videoData.title;
}
onYouTubeIframeAPIReady();

Retrieving individual videos view count - Youtube API V3.0 - JavaScript

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

Retrieve number of items in playlist with YouTube API v3

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

Is there a YouTube API that can give me structured metadata about a video?

Using the YouTube API, how can I fetch structured data about a video? For instance, given a video that is a movie trailer, how can I find the movie title or topic in a structured format, and other interesting metadata such as the celebrities featured or the director?
Yes. The v3 API allows you do do this via videos/list. Here's an example API call using a trailer for The Dark Knight Rises:
GET https://www.googleapis.com/youtube/v3/videos?part=topicDetails&id=g8evyE9TuYk&fields=items%2FtopicDetails%2FtopicIds&key={YOUR_API_KEY}
(To get a developer key, follow the instructions in our video tutorial).
That sets:
topic: topicDetails
id: g8evyE9TuYk
fields: items/topicDetails/topicIds
In the response body, you get:
{
"items": [
{
"topicDetails": {
"topicIds": [
"/m/0bpm4yw",
"/m/01d5g",
"/m/0btpm6",
"/m/0184dt",
"/m/02vxn"
]
}
}
]
}
These correspond to Freebase mids, which you can lookup using the Freebase API. For instance, the first response corresponds to the Freebase entity The Dark Knight Rises (movie). Once you look up the entity, you can look up related entities such as the director, actors, or genre.
Play around with the API explorer a bit. When you're ready to translate this into code, watch out video about turning the API reference into code.
I found that I got the metadata details I wanted via this request url:
https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id={YouTubeVideoID}&key={YourAPIkey}
Here is documentation with description of all the returned data fields.
Here's info on how to get an API key.

YouTube API V3 recordingDetails object missing in the response

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

Resources