Using YouTube API to embed videos dinamically on your web site

02 November, 2011 - 5 min read

It is easy to embed a given YouTube video on a web site, simply use the wizard to get code required code, but what about to do the some automatically using JavaScript? Yes, suppose you have a preferred user you follow all his videos and would like to put his/her latest video in your web site.

Every YouTube video has a unique identifier so the challenge is how to get the id if the latest uploaded (or updated if you prefer) video.

Searching for videos

YouTube has a very rich API and you have lot of parameters available to use, but, probably most important are the ways to search. Mainly you have two options to search videos for a given user:

  • Search video feeds:
  • Search videos uploaded for specific user:

First way is more flexible than second, because you can use lot of parameters to chose and author, limit results number, order by, etc, while the second is like setting the author parameter in the first one.

IMPORTANT !!! Read careful the YouTube API documentacion, concretely the sentence:

Requests using other parameters, such as orderby, will return cached results.

That makes me (on other folks) spent lot of time trying to find way searched doesn't get really updated results.

The requests

What will be our test request? Yeah !!! We are going to check for the lastest video of the user... ironmaiden !!!

We want to get maximum one videos from ironmaiden user and ordered by date of publication. In addition, we want the response be in JSON format (not in XML) so we use the 'alt' parameter too:



The response

By default, the returning data is specified in XML format (see here) but with the help of alt=jsonc parameter it is returned in JSON notation (see here). For the previous first request the response is:

            "title":"IMTV London",
            "description":"A quick IMTV from the O2. The full IMTV UK episode will be available to fanclub members soon!",
            "tags":["iron","maiden","imtv","on","board","flight","666","Iron Maiden","United Kingdom","Metal"],

As you can see the ID of the video is at:


Embeding a video

Embeding a video by hand is easy, you simply click on "share" button, then on "embed", copy and paste the code and that's all:

youtube embed 251x300 But hey !!! We are bad boys, worst if it is possible, we are programmers and we live to programming, so we are going to do the same than any other mortal but programming, so program once run forever !!! (mmm... that slogan sounds me like a island name programming language).

The intention is to make the code necessary to get the latest video identifier and inject the code to embed video on page, like this:

<iframe width="420" height="315" src="http://www.youtube.com/embed/PieS0zG228A"
frameborder="0" allowfullscreen></iframe>

Automatically embedding the latest video

Finally arrive to the most interesting section. As you can imagine we can do it in the AJAX way, making an asynchronous request and injecting the code but in addition I will put a more "static" way to do, thanks to the callback parameter in the request.

The AJAX way

First, create div elements to contain the video frame and a button to start the loading process:

<div id="ajax_video"></div>
<button id="ajaxbutton">AJAX way</button>

In the head section of the document Ihave added the required JavaScript code (I'm using jQuery to do it):

<script type="text/javascript">
            function(response) {
                if(response.data && response.data.items) {
                    var items = response.data.items;
                    if(items.length>0) {
                        var item = items[0];
                        var videoid = "http://www.youtube.com/embed/"+item.id;
                        console.log("Latest ID: '"+videoid+"'");
                        var video = "<iframe width='420' height='315' src='"+videoid+"' frameborder='0' allowfullscreen></iframe>";

As we mention, the request get the latest video from ironmaiden user, creates an iframe element containing it and add it to the previously created div element.

Using callback parameter

This version differs from previous one because the request is made when page is loaded. What I'm saying? Exactly this, the request is made including JavaScript code:

<script type="text/javascript" src="https://gdata.youtube.com/feeds/api/users/ironmaiden/uploads?max-results=1&orderby=published&v=2&alt=jsonc&callback=showVideo"></script>

The url includes the callback parameter which is responsible to call the specified function once the code is loaded.

Putting it all together, in the same way that previous case you need a div element that contains the video iframe and a JavaScript code to add the iframe from the response:

<div id="static_video"></div>
<script type="text/javascript">
    function showVideo(response) {
        if(response.data && response.data.items) {
            var items = response.data.items;
            if(items.length>0) {
                var item = items[0];
                var videoid = "http://www.youtube.com/embed/"+item.id;
                console.log("Latest ID: '"+videoid+"'");
                var video = "<iframe width='420' height='315' src='"+videoid+"' frameborder='0' allowfullscreen></iframe>";
<script type="text/javascript" src="https://gdata.youtube.com/feeds/api/users/ironmaiden/uploads?max-results=1&orderby=published&v=2&alt=jsonc&callback=showVideo"></script>

The browser load the elements in the order it encounters, so it is important to put the code in the right place so browser finds first the 'showVideo' function before loading the YouTube code request.


You can see a demo working here.





© I built this site withGatsbyfrom the starterjuliaand made a bunch of modifications. The full content is available in myrepository. Icons made byFreepik from Flaticon