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

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

A user can see all their videos on the YouTube website itself. But if you want to share the video list with someone then you have to keep this data offline. On the other hand, some users may want to display a video list on their website.

That being said, let’s have a look at how to get a list of YouTube videos using the YouTube API.

Note: Using the code of this article you can get a list of videos of any YouTube channel providing a valid YouTube channel id.

Get Your API Key

To get started with the YouTube API, you first need to create an API key from your Google account. 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 stand for configuration, helper methods, Ajax handling, and display the final result.

  • config.php : In this file, we set the API key as a constant. 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 a form to enter the YouTube channel id, give an Ajax, and display the video list.

In the config.php file, let’s declare the API key as a constant variable. I’d also define the helper method which will interact with the API endpoint.

<?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. 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 number of videos to return. 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 via GET parameter. So on the top of the same file, I will 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 video information. To display the result add the below code after your form.

I am not going to focus on the design of a list. 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. If we get the value of nextPageToken we are 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 this nextPageToken value. On the click of Load More, we’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.

<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>

For this article, 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 channel id, max_result, and nextPageToken.

The above code gives a call to the ajax.php file. This file will give us 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);

Our JavaScript code receives this JSON response and appends the result to the existing list of YouTube videos. This process continues until we find 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 playlist’s id. 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 on a YouTube channel. For a sake of the tutorial, in the first example, I am only 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.

Related Articles

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

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

Leave a Reply

Your email address will not be published.