In this YouTube Trending Videos Api tutorial, we will be writing the code to call the YouTube Data API V3 to fetch the most popular or the top 10 trending videos right now on YouTube.
Table of Contents
We’ll walk through the process of using PHP and cURL to fetch the most popular YouTube videos using the YouTube Data API. We’ll be using the curl_init()
and curl_exec()
functions to make an HTTP request to the YouTube API and handle the response.
Requirements
- YouTube API Key (follow this guide to create YouTube API Key)
- Basic knowledge of PHP
Steps to Get Trending YouTube Videos Using the YouTube Data API
Step 1: Set Up Your YouTube API Key
Before you begin, you need to obtain a YouTube API Key. If you don’t have one, you can create a project on the Google Cloud Console, enable the YouTube Data API v3, and generate an API Key.
Replace the placeholder $YOUTUBE_API_KEY
in the code with your actual API Key.
$YOUTUBE_API_KEY = "YOUR_ACTUAL_API_KEY";
Step 2: Specify API Parameters
Define the parameters for the YouTube API request. In this example, we are fetching the most popular videos in a specific country ($regionCode
) and video category ($category
). Adjust these values according to your requirements.
$regionCode = "IN"; // Specify the country code you want to search trending videos for
$category = "1"; // Specify the video category (e.g., 1 for Film & Animation)
$maxResults = 10; // Adjust the number of results as needed
Step 3: Build the API Request URL
Construct the API request URL by combining the YouTube API endpoint and the specified parameters using the http_build_query()
function.
$youtube_api_url = 'https://www.googleapis.com/youtube/v3/videos';
$params = [
'part' => 'snippet',
'chart' => 'mostPopular',
'regionCode' => $regionCode,
'videoCategoryId' => $category,
'maxResults' => $maxResults,
'key' => $YOUTUBE_API_KEY,
];
$url = $youtube_api_url . '?' . http_build_query($params);
Here is the break down of the important parameters used in our YouTube Data API request:
'part' => 'snippet'
:
- Purpose: This parameter specifies the parts of the video resource that the API response will include. In this case, it’s set to ‘snippet’.
- Explanation: The ‘snippet’ part includes basic details about the video, such as its title, description, thumbnails, and other metadata. Including ‘snippet’ ensures that the API response contains key information about the video.
'chart' => 'mostPopular'
:
- Purpose: Specifies the chart that the API should use to retrieve videos. In this case, it’s set to ‘mostPopular’.
- Explanation: When set to ‘mostPopular’, the API will return a list of videos that are currently popular, based on factors such as view count and user engagement. This allows you to retrieve trending or popular videos on YouTube.
'regionCode' => $regionCode
:
- Purpose: Specifies the region for which you want to retrieve popular videos. It’s dynamically set based on the
$regionCode
variable. - Explanation: By providing a specific region code (e.g., ‘US’ for the United States or ‘IN’ for India), you can tailor the results to reflect the popularity of videos in that particular region. If this parameter is not provided, the default region is usually set to ‘US’.
'videoCategoryId' => $category
:
- Purpose: Allows you to filter the videos based on a specific category. It’s dynamically set based on the
$category
variable. - Explanation: YouTube has predefined categories for videos (e.g., ‘Film & Animation’, ‘Music’, etc.). By setting the
videoCategoryId
parameter, you can narrow down the results to include videos that belong to a specific category. In the example, the value ‘1’ is used, which typically corresponds to the ‘Film & Animation’ category.
These parameters collectively help customize the YouTube Data API request to fetch the most popular videos in a specific region, category, and with essential details included in the response. Adjusting these parameters allows you to tailor the API request to meet your specific requirements.
Step 4: Make the API Request using cURL
Initialize a cURL session, set the necessary options, and execute the request.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
$output = 'Error: ' . curl_error($ch);
} else {
// Process and display the JSON response
echo "<pre>";
print_r(json_decode($response, true));
echo "</pre>";
}
curl_close($ch);
Step 5: Run the Script
Save the PHP script to a file (e.g., youtube_api.php
) and run it in a web browser or via the command line. The script will make a request to the YouTube API, retrieve the most popular videos based on the specified parameters, and display the response in a readable format.
Complete Code: YouTube Most Popular Videos API
<?php
$regionCode = "IN";
$category = "1";
$YOUTUBE_API_KEY = "AIzaSyCBiA7ZQtOnDgvdrRCtXp6Kpe_Q2C3NxZY";
$youtube_api_url = 'https://www.googleapis.com/youtube/v3/videos';
$params = [
'part' => 'snippet',
'chart' => 'mostPopular',
'regionCode' => $regionCode, //Optional: By deafult it is US
'videoCategoryId' => $category, // Optional: Specify a category
'maxResults' => 10, // Adjust as needed
'key' => $YOUTUBE_API_KEY,
];
$url = $youtube_api_url . '?' . http_build_query($params);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
$output = 'Error: ' . curl_error($ch);
}
else {
echo "<pre>";
print_r(json_decode($response, true));
echo "</pre>";
}
curl_close($ch);
?>
YouTube Trending Videos API Data Example
If everything goes fine and there is no error with your api key or the code then YouTube API will return the trending videos data similar to the following.
Array
(
[kind] => youtube#videoListResponse
[etag] => DlcO0hQVhZ2sQIUCQifp636OqvE
[items] => Array
(
[0] => Array
(
[kind] => youtube#video
[etag] => 0ItK3lorRdswwHKzphOYIkYBvwI
[id] => 6SXC-xsVBcc
[snippet] => Array
(
[publishedAt] => 2024-01-18T07:08:45Z
[channelId] => UCv-yge5mA1i9P3ahJaOBWcQ
[title] => पड़ोसन का चक्कर है😜😂 #youtubeshorts #comedy #biwino1 #kajalsoni #funny #drama
[description] =>
[thumbnails] => Array
(
[default] => Array
(
[url] => https://i.ytimg.com/vi/6SXC-xsVBcc/default.jpg
[width] => 120
[height] => 90
)
[medium] => Array
(
[url] => https://i.ytimg.com/vi/6SXC-xsVBcc/mqdefault.jpg
[width] => 320
[height] => 180
)
[high] => Array
(
[url] => https://i.ytimg.com/vi/6SXC-xsVBcc/hqdefault.jpg
[width] => 480
[height] => 360
)
[standard] => Array
(
[url] => https://i.ytimg.com/vi/6SXC-xsVBcc/sddefault.jpg
[width] => 640
[height] => 480
)
[maxres] => Array
(
[url] => https://i.ytimg.com/vi/6SXC-xsVBcc/maxresdefault.jpg
[width] => 1280
[height] => 720
)
)
[channelTitle] => Kajal Soni
[categoryId] => 22
[liveBroadcastContent] => none
[localized] => Array
(
[title] => पड़ोसन का चक्कर है😜😂 #youtubeshorts #comedy #biwino1 #kajalsoni #funny #drama
[description] =>
)
)
)
[1] => Array
(
[kind] => youtube#video
[etag] => 5yf6sgr23RoykWN55qPeaOkuH2g
[id] => GHCnFvWWloE
[snippet] => Array
(
[publishedAt] => 2024-01-18T14:06:55Z
[channelId] => UC9Ako-tkzLUfQZmUSW3gRgg
[title] => Dadi Ne Ghar Se Bhaga Diya 🤣🫢 #shorts #RamRamJi #comedy #funny
[description] => Dadi Ne Ghar Se Bhaga Diya
[thumbnails] => Array
Summary
That’s it! You’ve successfully created a PHP script to interact with the YouTube Data API and fetch the most popular videos. Feel free to customize the parameters and integrate this script into your projects as needed.
Now, you can write the additional code to present the data returned in a nice grid format like I have done here.