How do I get a YouTube video thumbnail from the YouTube API?

Nadia S.

The Problem

Without using the YouTube API, I can get the default thumbnail image of a video by placing the video ID in the following URL pattern:

Click to Copy
https://i.ytimg.com/vi/<video-id-here>/default.jpg

But how can I get a YouTube video thumbnail using the YouTube API?

The Solution

The YouTube API provides us with several thumbnail image URLs in the JSON data it returns. We can write a PHP script that gets a specific thumbnail image of a YouTube video, given its URL.

For example, we find the following five thumbnail image URLs under the thumbnails key nested in the raw JSON data returned by the YouTube API:

Click to Copy
// 'default' key (size: 120 x 90) https://i.ytimg.com/vi/hEwpjRHRpC8/default.jpg // 'medium' key (size: 320 x 180) https://i.ytimg.com/vi/hEwpjRHRpC8/mqdefault.jpg // 'high' key (size 480 x 360) https://i.ytimg.com/vi/hEwpjRHRpC8/hqdefault.jpg // 'standard' key (size 480 x 360) https://i.ytimg.com/vi/hEwpjRHRpC8/sddefault.jpg // 'maxres' key (size 1280 x 720) https://i.ytimg.com/vi/hEwpjRHRpC8/maxresdefault.jpg

The thumbnail images these URLs refer to differ by size and quality.

Let’s write an example PHP script to return the high-resolution thumbnail to our browser.

The first thing to do is to get your unique API key from the YouTube Data API.

Our script will do the following:

  • Extract the video ID from the URL.
  • Create the API endpoint with the video ID and our API key.
  • Use curl to make a GET request for the video’s JSON data.
  • Extract the thumbnail from the JSON data and display it in the browser.

Extract the YouTube Video ID

A YouTube video’s URL includes the video ID after v=. We can write a function that uses the parse_url() and parse_str() functions to get hold of the query part of the URL to find the ID that follows it.

Click to Copy
// URL of Sentry's 'Adding Source Maps for JavaScript Projects' video $url = "https://www.youtube.com/watch?v=hEwpjRHRpC8"; function getVideoId($url) { $urlData = parse_url($url); parse_str($urlData['query'], $queryInfo); return $queryInfo['v']; } // display the return value to test that the function works echo getVideoId($url);

The output matches the end of the $url string, which is the video’s ID:

Click to Copy
hEwpjRHRpC8

Construct the API Endpoint

Now we’ll concatenate the video ID and our API key to construct the endpoint we’ll use to get the details we need from the YouTube Data API.

Click to Copy
// get the video ID $videoId = getVideoId($url); // replace with your API key value $mySecretKey = "my-secret-api-key"; $myEndPoint = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" . $videoId . "&key=" . $mySecretKey;

Send a GET Request for the Video Data

We use curl to get the video’s JSON data, which we’ll use to form the thumbnail’s URL in the next step. We start the curl session and save it to the $ch (curl handle) variable. We use the curl handle to set options and make a GET request. Then we use curl_exec() to return the JSON data.

Click to Copy
// initialize the session $ch = curl_init(); // pass in the endpoint we constructed earlier curl_setopt($ch, CURLOPT_URL, $myEndPoint); // configure the response not to display in the browser curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // save the JSON data that is received $response = curl_exec($ch); // close the curl session curl_close($ch);

We use the curl_setopt function to set the options of our curl session, set up the request, and pass in our $myEndPoint URL. We use curl_setopt again to configure the response to be returned as a string (rather than output to the browser) so that we can work with it.

Put the JSON Data in an Associative Array

Now we can place the JSON data saved to the $response variable in a PHP array.

Click to Copy
$data = json_decode($response, true); // output the PHP array of video data print_r($data);

The PHP json_decode() function takes the $response data and converts it to a PHP array. We use the true value to have the function return the data as an associative array instead of an object.

This is what the beginning of the array looks like:

Click to Copy
Array ( [kind] => youtube#videoListResponse [etag] => //...etc )

Get the Thumbnail of the YouTube Video and Display it in the Browser

We’ll get the high-resolution video thumbnail URL from the array as follows:

Click to Copy
$thumbnailUrl = $data['items'][0]['snippet']['thumbnails']['high']['url'];

Finally, we can display the thumbnail image in our browser by wrapping the URL in the <img> HTML tag. For example:

Click to Copy
echo '<img src="' . $thumbnailUrl . '">';

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.