Get YouTube Video List By Keywords Using YouTube Search API and JavaScript

In the past, we have published an article How To Get YouTube Video List By Keywords Using YouTube Search API which was written for PHP developers. One of our readers looking for the same solution but in JavaScript and asked how to integrate the same API in the JavaScript. In this article, we study how to search YouTube videos by keyword in JavaScript using a YouTube search API. A user can also use this solution in their JavaScript-based applications which are built-up on ReactJS, AngularJs, NodeJS, etc.

Get Your API Key

In order to get hands dirty with YouTube API, we first need to get our API key. This key is necessary while interacting with the YouTube APIs. Without this key YouTube considers all incoming API call as unauthorized. You will find the step by step guide on creating API key on the official documentation. So follow the instructions and grab your API key.

Create a User Interface

As we are going to get YouTube video list by keyword let’s build a simple form where user can enter their keyword. We also add two more fields where user can pick a number of videos to return and can choose the search by option. You can search YouTube video on the basis of Date, Rating, Relevance, Title, or View count.

Create a index.html file and add the following code in it.

<form id="yt-form">
    <p><input type="text" id="keyword-input" placeholder="Enter keyword" required></p>
    <p><input type="number" id="maxresult-input" placeholder="Max Results" min="1" max="50" required></p>
    <p>
        <select id="order-input" required>
            <option value="">--SELECT ORDER--</option>
            <option value="date">Date</option>
            <option value="rating">Rating</option>
            <option value="relevance">Relevance</option>
            <option value="title">Title</option>
            <option value="viewCount" selected>View Count</option>
        </select>
    </p>
    <p>
        <input type="submit" value="Submit">
    </p>
</form>

<div id="videoListContainer"></div>

<script src="https://apis.google.com/js/api.js"></script>
<script src="script.js"></script>

In the above code, we have added id for each form input which will use the get input values. It also has empty div with id ‘videoListContainer’ where our video list would append. We have included two JS files – one is from Google and other is our own JS where we will write the code for YouTube search API.

YouTube Search API in JavaScript

When it comes to JavaScript, we first need to load Google API client with the help of the API key. Once we load Google API client they allow us to call their APIs. So let’s create script.js file and load the Google API client as follows.

gapi.load("client", loadClient);

function loadClient() {
    gapi.client.setApiKey("YOUTUBE_API_KEY");
    return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
                function(err) { console.error("Error loading GAPI client for API", err); });
}

Make sure to add your API key to the setApiKey method. If you have set up it correctly then in the browser console you should see the message ‘GAPI client loaded for API’ which is nothing but go ahead signal.

Call the API and Render Result

We all set now to call YouTube search API and display the result in our HTML. There are 2 things where we need to call the API. Search should initiate on the click of submit button and on paginate links. Of course, YouTube has a number of videos for a keyword. So we will add paginate links along with the video list.

To handle both these scenarios our code will be as follows. Below code also goes inside script.js file.

const ytForm = document.getElementById('yt-form');
const keywordInput = document.getElementById('keyword-input');
const maxresultInput = document.getElementById('maxresult-input');
const orderInput = document.getElementById('order-input');
const videoList = document.getElementById('videoListContainer');
var pageToken = '';

ytForm.addEventListener('submit', e => {
    e.preventDefault();
    execute();
});

function paginate(e, obj) {
    e.preventDefault();
    pageToken = obj.getAttribute('data-id');
    execute();
}

// Make sure the client is loaded before calling this method.
function execute() {
    const searchString = keywordInput.value;
    const maxresult = maxresultInput.value;
    const orderby = orderInput.value;

    var arr_search = {
        "part": 'snippet',
        "type": 'video',
        "order": orderby,
        "maxResults": maxresult,
        "q": searchString
    };

    if (pageToken != '') {
        arr_search.pageToken = pageToken;
    }

    return gapi.client.youtube.search.list(arr_search)
    .then(function(response) {
        // Handle the results here (response.result has the parsed body).
        const listItems = response.result.items;
        if (listItems) {
            let output = '<h4>Videos</h4><ul>';

            listItems.forEach(item => {
                const videoId = item.id.videoId;
                const videoTitle = item.snippet.title;
                output += `
                    <li>${videoTitle} (${videoId})</li>
                `;
            });
            output += '</ul>';

            if (response.result.prevPageToken) {
                output += `<br><a class="paginate" href="#" data-id="${response.result.prevPageToken}" onclick="paginate(event, this)">Prev</a>`;
            }

            if (response.result.nextPageToken) {
                output += `<a href="#" class="paginate" data-id="${response.result.nextPageToken}" onclick="paginate(event, this)">Next</a>`;
            }

            // Output list
            videoList.innerHTML = output;
        }
    },
    function(err) { console.error("Execute error", err); });
}

Here we are first getting our input values and store it in variables. In the execute method we write a code which gives a call to the YouTube API. In response, we get the list of video information along with either prevPageToken or nextPageToken or both. These token used to get a set of next or previous video list by keyword. We are appending these tokens as data attributes to our pagination links. Now when we click on paginate links API call initiate again, perform its task and give us correspondent response back. From the API response, we are displaying video information inside div which having the id ‘videoListContainer’.

Video List

In our tutorial, we are displaying video title and video id in the list. You can also print other information of videos in the list as per your requirement. You can log the variable listItems to check what kind of information YouTube API returns in the response.

You may also like to read our below articles written for other uses of YouTube APIs.

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

1 thought on “Get YouTube Video List By Keywords Using YouTube Search API and JavaScript

Leave a Reply

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