YouTube API – How to Get List of YouTube Videos of Your Channel

Recently one of our readers asked about getting a list of videos on a YouTube channel. They wanted to show their video list in tabular format on the website. In this article, we study how to use YouTube API to fetch a list of YouTube videos from your channel.

User can see all their videos on the YouTube website itself. But sometimes you may want to display a video list on the website. By placing videos on the website, you remove the noise of other suggested videos on YouTube. It also helps to improve the engagement of visitors.

Another reason for fetching a video list is you may want to share video URLs in bulk with someone and for that reason, you want to keep it offline(Excel, database, etc.)

Having said that, let’s study how to get a list of YouTube videos using the YouTube API.

Note: Following this tutorial, you can get a video list from any YouTube channel providing a valid channel id.

Get Your API Key

To get started with the YouTube API, you first need to create an API key on the Google Developer Console. This key is necessary while interacting with the YouTube APIs. The API call will not succeed unless you pass the valid API key in each request. Without an API key, YouTube considers all incoming requests as unauthorized.

Follow the steps below to create an API Key.

  • Go to the Google Developer Console.
  • Create a new project. You can also select the existing project.
  • Type the name of your project. Google Console will create the unique project ID.
  • After creating a project, it will appear on top of the left sidebar.
  • Click on Library. You will see a list of Google APIs.
  • Search for YouTube Data API and enable it.
  • Click on the Credentials. Select the API key under Create credentials.
  • Copy the API key. We will require it in the next step.
API key

Get a List of YouTube Videos

Once you are ready with the API key, create 3 files in your project. These files will be responsible for configuration, helper methods, Ajax handling, and display of the final result.

  • config.php : In this file, we’ll set the API key as a constant variable. It also has a helper method that gives an API call and returns a response.
  • ajax.php : This file will call the API to get the next set of results.
  • index.php : It contains The HTML form to enter the YouTube channel id, give an Ajax call, and display the video list.

config.php

<?php
define('GOOGLE_API_KEY', 'PASTE_YOUR_API_KEY');
 
function getYTList($api_url = '') {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $arr_result = json_decode($response);
    if (isset($arr_result->items)) {
        return $arr_result;
    } elseif (isset($arr_result->error)) {
        //var_dump($arr_result); //this line gives you error info if you are not getting a video list.
    }
}

Make sure to replace the placeholder with the actual API key. Note that to execute the API call, you should have the cURL extension enabled on your server.

Create a Form

Next, create a simple form where you can enter the YouTube channel id and the number of videos you wish to fetch. YouTube API returns a maximum of 50 videos at a time.

<form method="get">
    <p><input type="text" name="channel" placeholder="Enter Channel ID" value="<?php if(array_key_exists('channel', $_GET)) echo $_GET['channel']; ?>" required></p>
    <p><input type="number" name="max_result" placeholder="Max Results" min="1" max="50" value="<?php if(array_key_exists('max_result', $_GET)) echo $_GET['max_result']; ?>" required></p>
    <p><input type="submit" value="Submit"></p>
</form>

I set the form method as GET. Upon form submission, it will send channel id and max_result into the GET request. To catch these values, on the top of the same file, write the code as follows:

<?php
require_once "config.php";
 
$arr_list = array();
if (array_key_exists('channel', $_GET) && array_key_exists('max_result', $_GET)) {
    $channel = $_GET['channel'];
    $url = "https://www.googleapis.com/youtube/v3/search?channelId=$channel&order=date&part=snippet&type=video&maxResults=". $_GET['max_result'] ."&key=". GOOGLE_API_KEY;
    $arr_list = getYTList($url);
}
?>

This code includes a configuration file, gets the parameters from the URL, builds an API URL, and then passes it to the helper method we created in the previous step.

In return, you should receive a response containing your video list. To display the result add the below code after your HTML form. I am not going to focus on the design. The main purpose of the tutorial is to present YouTube videos. I’ll display them in the list format.

<?php
if (!empty($arr_list)) {
    echo '<ul class="video-list">';
    foreach ($arr_list->items as $yt) {
        echo "<li>". $yt->snippet->title ." (". $yt->id->videoId .")</li>";
    }
    echo '</ul>';
 
    if (isset($arr_list->nextPageToken)) {
        echo '<input type="hidden" class="nextpagetoken" value="'. $arr_list->nextPageToken .'" />';
        echo '<div id="loadmore">Load More</div>';
    }
}
?>

Here I am looping through the videos and printing the video title and video id. You can print the other information as well depending on your requirement. Print the variable $arr_list and you will see all details received from API.

If we get the value of nextPageToken I’m adding a hidden field and a Load More element. This is because if you have more than 50 videos on the channel, you can get the next set of records using the value of nextPageToken. When you click Load More, it’ll give an Ajax call and fetch the next set of videos.

Ajax Call

Write the below JavaScript code at the end of the index.php file. I am using vanilla JavaScript for the Ajax call and appending the response to the DOM. To the Ajax file, I am sending the values of the channel id, max_result, and nextPageToken.

<script>
var httpRequest, nextPageToken;
document.getElementById("loadmore").addEventListener('click', makeRequest);
function makeRequest() {
    httpRequest = new XMLHttpRequest();
    nextPageToken = document.querySelector('.nextpagetoken').value;
    if (!httpRequest) {
        alert('Giving up : Cannot create an XMLHTTP instance');
        return false;
    }
    httpRequest.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200) {
            var list = JSON.parse(this.responseText);
            for(var i in list) {
                if(list[i].title != undefined && list[i].id != undefined) {
                    var newElement = document.createElement('li');
                    newElement.innerHTML = '<li>'+ list[i].title +'('+ list[i].id +')</li>';
                    document.querySelector('.video-list').appendChild(newElement);
                }
            }
 
            if(list[list.length-1].nextPageToken != undefined) {
                document.querySelector('.nextpagetoken').value = list[list.length-1].nextPageToken;
            } else {
                var loadmore = document.getElementById("loadmore");
                loadmore.parentNode.removeChild(loadmore);
            }
        }
    };
    httpRequest.open('GET', 'ajax.php?channel=<?php echo $_GET['channel']; ?>&max_result=<?php echo $_GET['max_result']; ?>&nextPageToken='+nextPageToken, true);
    httpRequest.send();
}
</script>

The above code gives a call to the ajax.php file. This file will provide the next set of records which will then append to the existing listing. 

In the Ajax file, with the help of the given parameters, I’ll build the API URL and call the helper method. After receiving the API result, I’ll create a JSON object containing video information. To the final response, I am also appending a nextPageToken value to get the next set of records on subsequent Ajax calls.

ajax.php

<?php
require_once "config.php";
 
$url = "https://www.googleapis.com/youtube/v3/search?channelId=". $_GET['channel'] ."&order=date&part=snippet&type=video&maxResults=". $_GET['max_result'] ."&pageToken=". $_GET['nextPageToken'] ."&key=". GOOGLE_API_KEY;
 
$arr_list = getYTList($url);
 
$arr_result = array();
if (!empty($arr_list)) {
    foreach ($arr_list->items as $yt) {
        array_push($arr_result, ['title' => $yt->snippet->title, 'id' => $yt->id->videoId]);
    }
    if (isset($arr_list->nextPageToken)) {
        array_push($arr_result, ['nextPageToken' => $arr_list->nextPageToken]);
    }
}
 
echo json_encode($arr_result);

The JavaScript code receives this JSON response and appends the result to the existing list of YouTube videos. This process continues until it finds the value for nextPageToken.

Get Videos From the Playlist

If you are looking to fetch videos by playlist, you can do it by calling the playlistItems endpoint. To this endpoint, you have to pass the ID of a playlist. Refer to the code below.

$arr_list = array();
$playlistId = "PASS_PLAYLIST_ID";
$url = "https://www.googleapis.com/youtube/v3/playlistItems?playlistId=$playlistId&part=snippet&maxResults=10&key=".GOOGLE_API_KEY;
$arr_list = getYTList($url);

I hope you understand how to get a list of videos from a YouTube channel. Please share your thoughts and suggestions in the comment below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

5 thoughts on “YouTube API – How to Get List of YouTube Videos of Your Channel

Leave a Reply

Your email address will not be published. Required fields are marked *