Free YouTube Video Info API (Title, Aspect Ratio, Thumbnail, Author) - Working 2024
Related to:: YouTube - YouTube API
Here’s a quick trick to get basic YouTube video info using the video ID and an official YouTube “API” URL, which gives us a fast response.
Basically, we’ll use the oembed
endpoint, which is typically used to get the embed code from a given YouTube URL.
This is the URL, you just need to change the url=
parameter or the ID of the video if you only have that.
https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=aHXi6JEPkcY&format=json
And this is the response we get, including some good information about the video:
- Title;
- Author name and URL;
- Video height and width (used to get the aspect ratio);
- Thumbnail URL and dimensions;
- Embed HTML code.
{
"title": "Dicas Laravel - Seja mais produtivo e escreva menos código - Parte 1",
"author_name": "Alan Rezende - Full Stack Developer",
"author_url": "https://www.youtube.com/@AlanRezende",
"type": "video",
"height": 113,
"width": 200,
"version": "1.0",
"provider_name": "YouTube",
"provider_url": "https://www.youtube.com/",
"thumbnail_height": 360,
"thumbnail_width": 480,
"thumbnail_url": "https://i.ytimg.com/vi/aHXi6JEPkcY/hqdefault.jpg",
"html": "\u003Ciframe width=\"200\" height=\"113\" src=\"https://www.youtube.com/embed/aHXi6JEPkcY?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen title=\"Dicas Laravel - Seja mais produtivo e escreva menos código - Parte 1\"\u003E\u003C/iframe\u003E"
}
I used the below function in PHP to get the info and return it as metadata.
public function handleYouTubeInfo() {
$video = YouTubeVideo::find(1);
$videoId = $this->extractYouTubeId($video->video_url);
$metadata = $this->fetchYouTubeMetadata($videoId);
// Metadata available here
}
private function fetchYouTubeMetadata($videoId)
{
try {
$url = "https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={$videoId}&format=json";
$response = file_get_contents($url);
if ($response === false) {
return null;
}
} catch (\Exception $e) {
return null;
}
return json_decode($response, true);
}
private function extractYouTubeId($url)
{
$pattern = '/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i';
if (preg_match($pattern, $url, $match)) {
return $match[1];
}
return null;
}