Get YouTube Video List by Keywords Using YouTube Search API

YouTube is the second-largest search engine in the world. Due to its immense popularity, many users integrate YouTube-related functionalities into their websites. This includes embedding YouTube videos, YouTube subscription buttons, YouTube video galleries, Video searches, etc. In this article, we study how to integrate YouTube search API into the website.

This article explains how one can implement the task of searching YouTube videos from their website. We’ll use YouTube search API to get videos based on keywords, filter them by available options(date, rating, etc.) and display the video list. I am going to print the video title and video id. The user can also print other information as per their requirement.

Getting Started

To get started, you first need to create an API key on your Google Console account. This key is necessary while interacting with the YouTube APIs. Without this key YouTube considers all incoming API calls as unauthorized.

Below are the steps to grab the API key.

  • Head over to the Google Developer Console.
  • Create a new project. Optionally, you can also select an existing project.
  • Give a name to your project. Google Console will create a unique project ID for you.
  • Your newly created project will appear on top of the left sidebar.
  • Click on Library from the left menu. You will see a list of Google APIs. Enable the YouTube Data API.
  • Next, from the left menu click on the Credentials. Select the API key under Create credentials.
  • Copy this API Key.
API key

Create the User Interface

For this tutorial, I’ll create the HTML form which has the following fields.

  • TextField to enter the keyword
  • Number field to choose the number of videos to return
  • Dropdown to choose the type of filter

YouTube API has a limit of 50 records at a time so we will keep a limit of 50 on the number fields.

We will also require pagination to get the next and previous records. In each API response, YouTube includes the nextPageToken and prevPageToken if they’re available. Using these values as a parameter with pageToken, we can fetch the next or previous set of records.

There are several options available for filter types which are ‘date’, ‘rating’, ‘relevance’, ‘title’, and ‘viewCount’. The user can select anyone and the final result will be filtered depending on the selected type.

<form method="get">
    <p><input type="text" name="q" placeholder="Enter keyword" value="<?php if(array_key_exists('q', $_GET)) echo $_GET['q']; ?>" 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>
        <?php $arr_orders = ['date', 'rating', 'relevance', 'title', 'viewCount']; ?>
        <select name="order" required>
            <option value="">--SELECT ORDER--</option>
            <?php foreach ($arr_orders as $order) { ?>
                <option value="<?php echo $order; ?>" <?php if(array_key_exists('order', $_GET) && ($order==$_GET['order'])) echo 'selected'; ?>><?php echo ucfirst($order); ?></option>
            <?php } ?>
        </select>
    </p>
    <input type="submit" value="Submit" />
</form>

Here we created a form that has 3 fields for entering a keyword, the number of records to return, and a filter type.

Integrate YouTube Search API

At this stage, we are ready with the API key and the HTML form. Next, we need to get form values and pass them to the YouTube API endpoint along with the API key. After this, we will process the final response.

<?php
$api_key = 'YOUR_API_KEY';

$arr_list = array();
if (array_key_exists('q', $_GET) && array_key_exists('max_result', $_GET) && array_key_exists('order', $_GET)) {
    $formatted_keyword = implode("+", explode(" ", $_GET['q']));
    $url = "https://www.googleapis.com/youtube/v3/search?q=$formatted_keyword&order=". $_GET['order'] ."&part=snippet&type=video&maxResults=". $_GET['max_result'] ."&key=". $api_key;
 
    if (array_key_exists('pageToken', $_GET)) {
        $url .= "&pageToken=". $_GET['pageToken'];
    }
 
    $arr_list = getYTList($url);
}
 
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)) {
        //print error $arr_result->error->message
        echo $arr_result->error->message;
    }
}
?>

The above code checks for query parameters of a keyword, max_result, and order value for sorting. It takes these values and passes them to the API endpoint. In return, it appends responses to the $arr_list variable. We will loop through this variable and print the information about the videos.

<?php
if (!empty($arr_list)) {
    echo '<ul>';
    foreach ($arr_list->items as $item) {
        echo "<li>". $item->snippet->title ." (Video ID: ". $item->id->videoId .")</li>";
    }
    echo '</ul>';
 
    $url = "?q=". $_GET['q'] ."&max_result=". $_GET['max_result'] ."&order=". $_GET['order'];
    if (isset($arr_list->prevPageToken)) {
        echo '<a href="'.$url.'&pageToken='.$arr_list->prevPageToken.'">Previous</a>';
    }
 
    if (isset($arr_list->nextPageToken)) {
        echo '<a href="'.$url.'&pageToken='.$arr_list->nextPageToken.'">Next</a>';
    }
}
?>

You can place this code after the form’s HTML. It will give you a listing of video titles, and video ids along with pagination links.

Our final code is as follows:

<?php
$api_key = 'YOUR_API_KEY';
 
$arr_list = array();
if (array_key_exists('q', $_GET) && array_key_exists('max_result', $_GET) && array_key_exists('order', $_GET)) {
    $formatted_keyword = implode("+", explode(" ", $_GET['q']));
    $url = "https://www.googleapis.com/youtube/v3/search?q=$formatted_keyword&order=". $_GET['order'] ."&part=snippet&type=video&maxResults=". $_GET['max_result'] ."&key=". $api_key;
 
    if (array_key_exists('pageToken', $_GET)) {
        $url .= "&pageToken=". $_GET['pageToken'];
    }
 
    $arr_list = getYTList($url);
}
 
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)) {
        //print error with $arr_result->error->message;
    }
}
?>
 
<form method="get">
    <p><input type="text" name="q" placeholder="Enter keyword" value="<?php if(array_key_exists('q', $_GET)) echo $_GET['q']; ?>" 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>
        <?php $arr_orders = ['date', 'rating', 'relevance', 'title', 'viewCount']; ?>
        <select name="order" required>
            <option value="">--SELECT ORDER--</option>
            <?php foreach ($arr_orders as $order) { ?>
                <option value="<?php echo $order; ?>" <?php if(array_key_exists('order', $_GET) && ($order==$_GET['order'])) echo 'selected'; ?>><?php echo ucfirst($order); ?></option>
            <?php } ?>
        </select>
    </p>
    <input type="submit" value="Submit" />
</form>
 
<?php
if (!empty($arr_list)) {
    echo '<ul>';
    foreach ($arr_list->items as $item) {
        echo "<li>". $item->snippet->title ." (Video ID: ". $item->id->videoId .")</li>";
    }
    echo '</ul>';
 
    $url = "?q=". $_GET['q'] ."&max_result=". $_GET['max_result'] ."&order=". $_GET['order'];
    if (isset($arr_list->prevPageToken)) {
        echo '<a href="'.$url.'&pageToken='.$arr_list->prevPageToken.'">Previous</a>';
    }
 
    if (isset($arr_list->nextPageToken)) {
        echo '<a href="'.$url.'&pageToken='.$arr_list->nextPageToken.'">Next</a>';
    }
}
?>

I hope you understand integrating YouTube search API into your website. You may read more about it in the documentation. Please share your thoughts and suggestions in the comment section below.

Related Articles

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

2 thoughts on “Get YouTube Video List by Keywords Using YouTube Search API

Leave a Reply

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