Get YouTube Video List by Keywords Using YouTube Search API

YouTube is the second largest search engine in the world. Due to their popularity, many websites integrate YouTube related functionalities to their website. This includes embedding YouTube videos, YouTube subscription button, YouTube video gallery, Video search, etc. In this article, we are going to see how to integrate YouTube search API to the website.

This article explains how one can implement the task of searching YouTube videos within a website. We’ll use YouTube search API to get videos based on keywords, filter it 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 print other information also 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 https://console.developers.google.com .
  • Create a new project. Optionally, you can also select existing project.
  • Give name to your project. Google Console will create 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 API key under Create credentials.
  • Copy this API Key.

API key

Create A User Interface

For this tutorial, I am going to create a form where a user can enter the keyword, choose a number of videos to return, and filter type. 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 add pagination to get the next and previous set of records. In each response, YouTube provides values for nextPageToken and prevPageToken if available. Using these values as a parameter like ‘pageToken=PageToken_VALUE’ in HTTP GET requests, we can fetch the next or previous set of records.

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

<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>
    <p><input type="submit" value="Submit"></p>
</form>

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

Integrate YouTube Search API

At this stage, we are ready with our API key and 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
    }
}
?>

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 response to the variable $arr_list. 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, 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 $arr_result->error
    }
}
?>

<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>
    <p><input type="submit" value="Submit"></p>
</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 to your website. 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 *