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

In the past, I 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 was looking for the same solution in JavaScript.

In this article, we study how to search YouTube videos by keyword with JavaScript using a YouTube search API. A user can use this solution in their JavaScript applications which are built on ReactJS, AngularJs, NodeJS, etc.

Get Your API Key

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 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 API key under Create credentials.
  • Copy this API Key.
API key

Create a User Interface

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

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

<!DOCTYPE html>
<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	    <meta http-equiv="X-UA-Compatible" content="ie=edge">
	    <title>Get YouTube Video by Keyword</title>
	    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" />
	    <style>
	    .paginate {
	        margin-right: 5px;
	    }
	    li {
	        display: inline-block;
	    }
	    </style>
	</head>
	<body>
	    <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="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>
	    <script src="js/custom.js"></script>
	</body>
</html>

In the above code, I have added ‘id’ to each form input which will be used to get the input values. It also has an empty div with id videoListContainer inside which our video list will display. I have included two JS files – one is from Google and the other is our own JS where we will write the code for YouTube search API. I also included Fancybox CSS and JS through CDN which will play YouTube videos in the pop-up.

YouTube Search API in JavaScript

When it comes to JavaScript, we first need to load the Google API client. Once we load Google API client, they allow us to call their APIs. Let’s create a js/custom.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 set it correctly then in the browser console you should see the message ‘GAPI client loaded for API’. It means we are good to go ahead.

Call the API and Render Result

We all set to call YouTube search API and display the result in the HTML. There are 2 things where we need to call the API. Search should initiate with the click of the submit button and on paginate links. YouTube returns a number of videos for a keyword search. So we will add paginate to navigate the next and previous set of videos.

To handle these scenarios, our code will be as follows. The below code also goes inside js/custom.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><a data-fancybox href="https://www.youtube.com/watch?v=${videoId}"><img src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" /></a><p>${videoTitle}</p></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 the input values from a Form and storing it in variables. In the execute method, we write a code that gives a call to the YouTube API. In response, we get the list of videos along with either prevPageToken or nextPageToken or both. These tokens are used to get a set of next or previous videos list by keyword. We are appending these tokens as data attributes to the pagination links. Now when we click on paginate links, the API call initiates again, performs its task, and gives us a response. From the API response, we are displaying video information inside the div which has the id videoListContainer.

YouTube Video List

In our tutorial, we are displaying video thumbnails and video titles on the list. You can also print other video information as per your requirement. The user may print the variable listItems to check what kind of information YouTube API returns in the response. Apart from it, I also used Fancybox in the above code using the data-fancybox attribute. This attribute will play the video in a pop-up.

I hope you got to know how to get a YouTube video list by keywords in JavaScript. 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.

12 thoughts on “Get YouTube Video List By Keywords Using YouTube Search API and JavaScript

    1. Hi Ben, I updated the code. You would see now fancybox integrated with it instead of embedded video. Fancybox is a better option rather than using the iframe tag.

Leave a Reply

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