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

To get a thumbnail image for a YouTube video in PHP, you can use the file_get_contents function to make a GET request to the videos.list method of the YouTube Data API.

Here's an example of how to do this:

<?php

// Replace YOUR_API_KEY with your actual API key
$apiKey = 'YOUR_API_KEY';

// Replace VIDEO_ID with the ID of the video for which you want to get the thumbnail
$videoId = 'VIDEO_ID';

// Set the API endpoint for the videos.list method
$apiEndpoint = 'https://www.googleapis.com/youtube/v3/videos';

// Set the parameters for the API request
$params = [
    'id' => $videoId,
    'key' => $apiKey,
    'part' => 'snippet,contentDetails',
];

// Build the query string
$query = http_build_query($params);

// Make the GET request to the API endpoint
$response = file_get_contents($apiEndpoint . '?' . $query);

// Decode the JSON response
$responseData = json_decode($response, true);

// Get the thumbnail image URL from the response data
$thumbnailUrl = $responseData['items'][0]['snippet']['thumbnails']['default']['url'];

// Use the thumbnail image URL to display the thumbnail image
echo '<img src="' . $thumbnailUrl . '" alt="Thumbnail">';

?>

Watch a course Learn object oriented PHP

This code makes a GET request to the videos.list method of the YouTube Data API, passing in the API key, the video ID, and the part parameter set to snippet,contentDetails. The API returns a JSON object containing data about the video, including the thumbnail image URL in the snippet.thumbnails.default.url field. The code then decodes the JSON response and extracts the thumbnail image URL, which it uses to display the thumbnail image.