Nadia S.
—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:
https://i.ytimg.com/vi/<video-id-here>/default.jpg
But how can I get a YouTube video thumbnail using the YouTube API?
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:
// '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:
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.
// 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:
hEwpjRHRpC8
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.
// 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;
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.
// 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.
Now we can place the JSON data saved to the $response
variable in a PHP array.
$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:
Array ( [kind] => youtube#videoListResponse [etag] => //...etc )
We’ll get the high-resolution video thumbnail URL from the array as follows:
$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:
echo '<img src="' . $thumbnailUrl . '">';
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.