Making Your First Get Request to Youtube Search API

aveb

Avery Berkowitz

Posted on October 7, 2019

Making Your First Get Request to Youtube Search API

When I was first introduced to APIs (Application programming interfaces), I was thrilled. How amazing is it that we can harness the power of one or many other applications within our own!? Then I tried to make my first request... Let's just say I spent the next few hours learning about every 400something error there is. So how do we actually get an API to talk back nicely? This article will walk you through making a simple GET request to the Youtube Search API using javascript and a bit of JQuery. Let's get to it!

Setting up your environment:

  1. Open up a new pen in CodePen
  2. Add Jquery to your .html file. We will need Jquery to make our request and to update a few HTML elements that we will add shorty.

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
    crossorigin="anonymous"></script>
    

If you have something against CodePen, feel free to create your files on your local machine and edit them in your favorite text editor.

  1. We need a few more HTML elements in order to display the data we will get back from the youtube API. Add the following to your .html file:

     <iframe src=""></iframe>
     <h3>Video Title</h3>
     <p class="description">Video Description<p>
    

At this point, your page should look like this:

  1. Get your API key. This is necessary in order to make requests to the Youtube Data API. Requests without this key will respond with one of those nasty 400 codes. Navigate to the google developers console. If you don't have an account, take a moment to set one up (It's Free!) . Once you are logged in, you will need to:
    • Create a new project
    • Enable Youtube Data API
    • Create Credentials
    • Copy Your API Key

Here's a quick video if you want to see how I got my key for this tutorial:
get your api key

Making a GET request

We've got our HTML template, we have our API key, now let's write some javascript. We will be using Ajax -- a feature built into JQuery in order to make our request. Let's write a function that will make a GET request to the youtube API. In this request we will be passing along some information to YouTube telling them that we want them to send us back some information about a video. With that information, we will be able to successfully embed the video in our page!

Our request function:

Place the following into your .js file:

    function getVideo() {
      $.ajax({
        type: 'GET',
        url: 'https://www.googleapis.com/youtube/v3/search',
        data: {
            key: 'PASTE YOUR API KEY HERE',
            q: "cats",
            part: 'snippet',
            maxResults: 1,
            type: 'video',
            videoEmbeddable: true,
        },
        success: function(data){
            embedVideo(data)
        },
        error: function(response){
            console.log("Request Failed");
        }
      });
    }
Enter fullscreen mode Exit fullscreen mode

Our getVideo() function calls a jquery method ajax. This message takes an object with some special properties to help us request and process our data. Let's break down the properties inside this ajax call.

  1. Our first property specifies that we are making a GET request.
  2. We then set our path to the youtube data API as a string.
  3. Next, we define a data property and create an object to contain all the necessary parameters that youtube needs. A key and part property are required by the API. Paste in your newly created API key (in quotes) and make sure you specify "snippet" as your part. This will ensure that we receive an object with all the info necessary to embed our video. I have added a few additional properties to make sure we get back viable data. In order to get back just one video, I have set maxResults to 1. type and videoEmbeddable ensure that I get back the data for a video that is actually able to be embedded into a site. Feel free to checkout the youtube search documentation to see all the options you can put in the data object.
  4. success will call a function with the data we receive back from our GET request. the ajax method will magically wait for us to receive the data before calling the function. In just a moment, we will write out embedVideo function inside, so just hang tight!
  5. Lastly, we assign error to a function that will log the server response if it is unsuccessful.

Using the Data Received from our Request

Time to see if we are getting anything back! Add the following code to process a successful request and render some data to the DOM.
Add the following to your .js file:

function embedVideo(data) {
    $('iframe').attr('src', 'https://www.youtube.com/embed/' + data.items[0].id.videoId)
    $('h3').text(data.items[0].snippet.title)
    $('.description').text(data.items[0].snippet.description)
}
Enter fullscreen mode Exit fullscreen mode

data is returned to us by our ajax message as an array. In the first line inside of our function, we use jquery to select our iframe element and update the src attribute. In order to embed a video, you must provide 'https://www.youtube.com/embed/' + the unique videoId that we can access within the data array from our request. Since we only are receiving one video, we access the 0 index with data.items[0] we then access the id property and finally, the videoId property. Quite the drilling, but expect this when working with most API's. The next two lines employ similar drilling down into the data array to retrieve the video's title and description, updating the h3 and p text on the DOM.

Finishing up!

Double check to make sure you have pasted in your API key to the getVideo function!!
Let's make our request! We must call our getVideo function. Add the following function invocation at the bottom of your .js file:

getVideo();
Enter fullscreen mode Exit fullscreen mode

At this point, here's what your app should look like:
preview

Try changing the q string inside your ajax request and watch the app update to a new video! Pretty cool, right? Check out the app on CodePen if you want to see all of the code together. I have taken out the youtube data API key so make sure you paste yours in so you can actually see some data displayed!

If you made it this far, hopefully you feel a little less lost making requests to APIs. Until next time!

Avery

Link to my CodePen for this post if you want to fork it

💖 💪 🙅 🚩
aveb
Avery Berkowitz

Posted on October 7, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related