Youtube API - Extract Video ID

How can I get a Youtube video ID from the Youtube API given the video url?

Doing a search with the API works with different YouTube URL types. The URL is passed as the query term q.

https://www.googleapis.com/youtube/v3/search/?key=<YOUR_KEY>&part=snippet&q=youtu.be/M7lc1UVf-VE

Maybe some case could result in more than one item, but the normal search result is just one match:

{
kind: "youtube#searchListResponse",
etag: ""m2yskBQFythfE4irbTIeOgYYfBU/j2Px-5q--mgJEsrfjg4L0Mgn_L8"",
regionCode: "ES",
pageInfo: {
totalResults: 1,
resultsPerPage: 5
},
items: [
{
kind: "youtube#searchResult",
etag: ""m2yskBQFythfE4irbTIeOgYYfBU/_1gFVi_i_djlS4OZWPGtcZ3iSLQ"",
id: {
kind: "youtube#video",
videoId: "M7lc1UVf-VE"
},
snippet: {
publishedAt: "2013-04-10T17:25:04.000Z",
channelId: "UC_x5XG1OV2P6uZZ5FSM9Ttw",
title: "YouTube Developers Live: Embedded Web Player Customization",
description: "On this week's show, Jeff Posnick covers everything you need to know about using player parameters to customize the YouTube iframe-embedded player.",
thumbnails: {
default: {
url: "https://i.ytimg.com/vi/M7lc1UVf-VE/default.jpg",
width: 120,
height: 90
},
medium: {
url: "https://i.ytimg.com/vi/M7lc1UVf-VE/mqdefault.jpg",
width: 320,
height: 180
},
high: {
url: "https://i.ytimg.com/vi/M7lc1UVf-VE/hqdefault.jpg",
width: 480,
height: 360
}
},
channelTitle: "Google Developers",
liveBroadcastContent: "none"
}
}
]
}

I tested with some of the URL variations from this answer and most worked:

var urls = [
'//www.youtube-nocookie.com/embed/M7lc1UVf-VE?rel=0',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=channel',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'https://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I', // <---- invalid
'https://youtu.be/M7lc1UVf-VE',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=youtu.be',
'https://youtu.be/M7lc1UVf-VE',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=channel',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'https://www.youtube.com/ytscreeningroom?v=M7lc1UVf-VE', // <---- invalid
'https://www.youtube.com/embed/M7lc1UVf-VE?rel=0',
'https://www.youtube.com/watch?v=M7lc1UVf-VE',
'https://youtube.com/v/M7lc1UVf-VE?feature=youtube_gdata_player',
'https://youtube.com/vi/M7lc1UVf-VE?feature=youtube_gdata_player', // <---- invalid
'https://youtube.com/?v=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://youtube.com/?vi=M7lc1UVf-VE&feature=youtube_gdata_player', // <---- invalid
'https://youtube.com/watch?v=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://youtube.com/watch?vi=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://youtu.be/M7lc1UVf-VE?feature=youtube_gdata_player'
];

var my_key = '<YOUR_KEY>';

function getUri(uri){
$.get('https://www.googleapis.com/youtube/v3/search/?key='+my_key+'&part=snippet&q='+uri, function(data) {
if(data.items.length !== 0)
console.log(data.items[0].snippet.publishedAt);
else
console.warn('no items for',uri)
});
}

for (i = 0; i < urls.length; ++i) {
getUri(urls[i]);
}

Youtube API - Extract video ID

Here is an example function that uses a regular expression to extract the youtube ID from a URL:

/**
* get youtube video ID from URL
*
* @param string $url
* @return string Youtube video id or FALSE if none found.
*/
function youtube_id_from_url($url) {
$pattern =
'%^# Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
$%x'
;
$result = preg_match($pattern, $url, $matches);
if ($result) {
return $matches[1];
}
return false;
}

echo youtube_id_from_url('http://youtu.be/NLqAF9hrVbY'); # NLqAF9hrVbY

It's an adoption of the answer from a similar question.


It's not directly the API you're looking for but probably helpful. Youtube has an oembed service:

$url = 'http://youtu.be/NLqAF9hrVbY';
var_dump(json_decode(file_get_contents(sprintf('http://www.youtube.com/oembed?url=%s&format=json', urlencode($url)))));

Which provides some more meta-information about the URL:

object(stdClass)#1 (13) {
["provider_url"]=>
string(23) "http://www.youtube.com/"
["title"]=>
string(63) "Hang Gliding: 3 Flights in 8 Days at Northside Point of the Mtn"
["html"]=>
string(411) "<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/NLqAF9hrVbY?version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/NLqAF9hrVbY?version=3" type="application/x-shockwave-flash" width="425" height="344" allowscriptaccess="always" allowfullscreen="true"></embed></object>"
["author_name"]=>
string(11) "widgewunner"
["height"]=>
int(344)
["thumbnail_width"]=>
int(480)
["width"]=>
int(425)
["version"]=>
string(3) "1.0"
["author_url"]=>
string(39) "http://www.youtube.com/user/widgewunner"
["provider_name"]=>
string(7) "YouTube"
["thumbnail_url"]=>
string(48) "http://i3.ytimg.com/vi/NLqAF9hrVbY/hqdefault.jpg"
["type"]=>
string(5) "video"
["thumbnail_height"]=>
int(360)
}

But the ID is not a direct part of the response. However it might contain the information you're looking for and it might be useful to validate the youtube URL.

trying to extract video id from json using youtube api

Suppose we have a jsonObject for this response.
Now as per your json response, following code will obtain videoId:

    JSONArray jArr = jsonObject.getJSONArray("items");
for(int i =0; i < jArr.length(); i++)
{
// getting object from items array
JSONObject itemObj = jArr.getJSONObject(i);

// getting id object from item object
JSONObject idObj = itemObj.getJSONObject("id");

// getting videoId from idObject
String videoId = idObj.getString("videoId");
}

Youtube v3 Api Get video by ID

YouTube API search call is for searches. You want to use the videos call and pass in the video ID(s) you want to query.

Example:

https://www.googleapis.com/youtube/v3/videos?part=snippet&id=xE_rMj35BIM&key=YOUR_KEY

How do I get the YouTube video ID from a URL?

You don't need to use a regular expression for this.

var video_id = window.location.search.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
video_id = video_id.substring(0, ampersandPosition);
}

Youtube API v3 get every Video ID from given channel

So I got a solution:

(1) First, I use https://www.googleapis.com/youtube/v3/channels?id=CHANNEL_ID&key=API_KEY&part=contentDetails to get the id of the Uploads Playlist.

(2) By using https://www.googleapis.com/youtube/v3/playlistItems?playlistId=UPLOAD_ID&key=API_KEY&part=snippet&maxResults=50
I get the first 50 results and a pageToken.

(3) With the token I can collect the IDs from the next pages:
https://www.googleapis.com/youtube/v3/playlistItems?playlistId=UPLOAD_ID&key=API_KEY&part=snippet&pageToken=PAGE_TOKEN&maxResults=50

(4) By using a recursive method, I can use the next Token I get from (3) to scan the next page.

How can I extract video ID from YouTube's link in Python?

Python has a library for parsing URLs.

import urlparse
url_data = urlparse.urlparse("http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1")
query = urlparse.parse_qs(url_data.query)
video = query["v"][0]

How to extract all YouTube comments using YouTube API? (Python)

From the answer of commentThreads, you have to add the replies parameter in order to retrieve the replies the comments might have.

So, your request should look like this:

video_response=youtube.commentThreads().list(part='id,snippet,replies',
videoId=video_id,
pageToken=token).execute()

Then, modify your code accordingly for read the replies of the comments.

In this example I made using the try-it feature available in the documentation, you can check that the reponse contains both, the top comment and its replies.


Edit (08/04/2022):

Create a new variable that contains the totalReplyCount that the topLevelComment might have.

Something like:

def get_comments(youtube, video_id, comments=[], token=''):

# Stores the total reply count a top level commnet has.
totalReplyCount = 0

# Replies of the top-level comment might have.
replies=[]

video_response=youtube.commentThreads().list(part='snippet',
videoId=video_id,
pageToken=token).execute()
for item in video_response['items']:
comment = item['snippet']['topLevelComment']
text = comment['snippet']['textDisplay']

# Get the total reply count:
totalReplyCount = item['snippet']['totalReplyCount']

# Check if the total reply count is greater than zero,
# if so,call the new function "getAllTopLevelCommentReplies(topCommentId, replies, token)"
# and extend the "comments" returned list.
if (totalReplyCount > 0):
comments.extend(getAllTopLevelCommentReplies(comment['id'], replies, None))
else:
comments.append(text)

# Clear variable - just in case - not sure if need due "get_comments" function initializes the variable.
replies = []

if "nextPageToken" in video_response:
return get_comments(youtube, video_id, comments, video_response['nextPageToken'])
else:
return comments

Then, if the value of totalReplyCount is greater than zero, make another call using the comment.list for bring the replies the top level comment has.
For this new call, you have to pass the id of the top level comment.

Example (untested):

# Returns all replies the top-level comment has: 
# topCommentId = it's the id of the top-level comment you want to retrieve its replies.
# replies = array of replies returned by this function.
# token = the comments.list might return moren than 100 comments, if so, use the nextPageToken for retrieve the next batch of results.
def getAllTopLevelCommentReplies(topCommentId, replies, token):
replies_response=youtube.comments().list(part='snippet',
maxResults=100,
parentId=topCommentId
pageToken=token).execute()

for item in replies_response['items']:
# Append the reply's text to the
replies.append(item['snippet']['textDisplay'])

if "nextPageToken" in replies_response:
return getAllTopLevelCommentReplies(topCommentId, replies, replies_response['nextPageToken'])
else:
return replies

Edit (11/04/2022):

I've added the Google Colab example I modified based on your code and it works with my video example (ouf0ozwnU84) = it brings its 130 comments, but, with your video example (BaGgScV4NN8) I got 3300 of 3359.

This might be some comments could be under approval/moderation or something else I'm missing or probably there are comments too old and additional filters are needed, or the API is buggy - see here some other questions related to troubles facing with the pagination using the API - I suggest you to check this tutorial which shows code and you can change it.



Related Topics



Leave a reply



Submit