Linking Dynamic Content from External Websites

Design and develop your very own responsive web applications using Java, jQuery, and AJAX.

(For more resources related to this topic, see here.)

Introduction to the YouTube API

YouTube provides three different APIs for a client application to access. The following figure shows the three different APIs provided by YouTube:

Configuring a YouTube API

In the Google Developers Console, we need to create a client project. We will be creating a new project, called PacktYoutubeapi. The URL for the Google Developers Console is https://console.developers.google.com.

The following screenshot shows the pop-up window that appears when you want to create a new client project in the Developers Console:

After the successful creation of the new client project, it will be available in the Console's project list. The following screenshot shows our new client project listed in the Developers Console:

There is an option available to enable access to the YouTube API for our application. The following screenshot shows the YouTube API listed in the Developers Console. By default, the status of this API is OFF for the application.

To enable this API for our application, we need to toggle the STATUS button to ON. The following screenshot shows the status of the YouTube API, which is ON for our application:

To access YouTube API methods, we need to create an API key for our client application. You can find the option to create a public API key in the APIs & auth section. The following screenshot shows the Credentials subsection where you can create an API key:

In the preceding screenshot, you can see a button to create a new API key. After clicking on this button, it provides some choices to create an API key, and after the successful creation of an API key, the key will be listed in the Credentials section. The following screenshot shows the API key generated for our application:

Searching for a YouTube video

In this section, we will learn about integrating a YouTube-related search video. YouTube Data API Version 3.0 is the new API to access YouTube data. It requires the API key that has been created in the previous section.

The main steps that we have to follow to do a YouTube search are:

  1. After adding the YouTube Search button, click on it to trigger the search process.
  2. The script reads the data-booktitle attribute to get the title. This will serve as a keyword for the search. Check the following screenshot for the HTML markup showing the data-booktitle attribute:

  3. Then, it creates an AJAX request to make an asynchronous call to the YouTube API, and returns a promise object.
  4. After the successful completion of the AJAX call, the promise object is resolved successfully.
  5. Once the data is available, we fetch the jQuery template for the search results and compile it with a script function. We then link it to the search data returned by the AJAX call and generate the HTML markup for rendering.

The base URL for the YouTube search is through a secure HTTP protocol, https://www.googleapis.com/youtube/v3/search. It takes different parameters as input for the search and filter criteria. Some of the important parameters are field and part.

The part parameter

The part parameter is about accessing a resource from a YouTube API. It really helps the application to choose resource components that your application actually uses. The following figure shows some of the resource components:

The fields parameter

The fields parameter is used to filter out the exact fields that are needed by the client application. This is really helpful to reduce the size of the response.

For example, fields = items(id, snippet(title)) will result in a small footprint of a response containing an ID and a title.

The YouTube button markup

We have added a button in our jQuery product template to display the search option in the product. The following code shows the updated template:

<script id="aProductTemplate" type="text/x-jquery-tmpl">
<div class="ts-product panel panel-default">
<div class="panel-head">
<div class="fb-like" data-href="${url}" datalayout="
button_count"
data-action="like" data-show-faces="true" datashare="
true"> </div> </div> <div class="panel-body">
<span class="glyphicon glyphicon-certificate ts-costicon">
<label>${cost}$</label>
</span>
<img class="img-responsive" src ="${url}">
<h5>${title}</h5>
</div>
<div class="panel-footer">
<button type="button" class="btn btn-danger btn-block
packt-youtube-button" data-bookTitle="${title}">YouTube Search</
button>

<button type="button" class="btn btn-info btn-block">Buy</
button>
<button type="button" class="btn btn-info btn-block twitme"
data-bookTitle="${title}" data-imgURI="${url}">Tweet</button>
<div class="g-plus-button">
<div class="g-plusone" data-width="180" datahref="${
url}"></div>
</div>
</div>
</div>
</script>

The following screenshot shows the updated product markup with a YouTube button added to the product template:

Asynchronous search in YouTube

When any user clicks on the YouTube Search button, a list of related videos will appear at the top of the page. In this article, we are mainly focusing on the search feature of YouTube using the keyword option. The query parameter that does this work is q.

The following URL shows an example of how to search the Cassandra Administration:

https://www.googleapis.com/youtube/v3/search?q=Cassandra+Administration&part=snippet&key=AIzaSyBTYn7fvH1mpIKlw8W5K4Ju-hNaievd9Fs

JSON's data object response for the preceding URL has five item objects as a response but due to the space constraint, only one item detail is listed as follows:

{
"kind": "youtube#searchListResponse",
"etag": "\"ePFRUfYBkeQ2ncpP9OLHKB0fDw4/7OUuUA4io00-
QTaWxOM2dzJxZ14\"",
"nextPageToken": "CAUQAA",
"pageInfo": {
"totalResults": 14063,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"ePFRUfYBkeQ2ncpP9OLHKB0fDw4/
BUpjVqlJL1lhr3TGWJnPVlmTM0g\"",
"id": {
"kind": "youtube#video",
"videoId": "UTE6kQXVa-M"
},
"snippet": {
"publishedAt": "2013-11-22T12:27:36.000Z",
"channelId": "UC3VydBGBl132baPCLeDspMQ",
"title": "Cassandra Administration Tutorial: Building a
Cluster of Multiple Nodes | packtpub.com",
"description": "Learn how to scale out a Cassandra cluster
from a single node. Prepare the seed node Configure the cluster
Conduct verification tests Part of Cassandra...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/UTE6kQXVa-M/
default.jpg"
},

"medium": {
"url": "https://i.ytimg.com/vi/UTE6kQXVa-M/
mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/UTE6kQXVa-M/
hqdefault.jpg"
}
},
"channelTitle": "packt1000",
"liveBroadcastContent": "none"
}
},
]
}

The response JSON format from YouTube is shown in the following screenshot:

The details of the fields are explained as follows:

  • kind: This represents a type of JSON object. As this JSON object is a list of search results, the type is searchListResponse.
  • etag: This represents the unique tag of this resource.
  • nextPageToken: This represents a unique token value that needs to be passed on the subsequent request in order to access the next set of results through pagination.
  • pageInfo: This consists of the pagination information:
    • totalResults: This returns the total number of results for a query.
    • resultsPerPage: This returns the maximum number of records per page.
  • items: This contains the actual result of the search.

The following screenshot shows the details of the items property:

The details of the fields are explained as follows:

  • kind: This represents a type of object. As this represents an individual record of every search, the type is seacrhResult.
  • etag: This represents a unique string for the resource object.
  • id: This represents a unique identifier and has two subfields kind and videoId:
    • kind: This represents the type as video.
    • videoId: This represents a unique video ID of the resultant video. This ID can further be used to embed videos to a page.
  • snippet: This represents the actual value of the video.

The following screenshot shows the inside details of the items property:

The details of the fields are explained as follows:

  • publishedAt: This represents the date and time of when the API is published.
  • channelId: This represents a unique channel identifier and designates the channel to which the video belongs.
  • title: This represents title of the video.
  • description: This represents the description of the video.
  • thumbnails: This contains the image URL for the video and has three different subfields:
    • default: This contains the URL for the thumbnail image with default quality.
    • medium: This contains the URL for the thumbnail image with medium quality.
    • high: This contains the URL for the thumbnail image with high quality.
  • channelTitle: This represents the name of the channel to which the video belongs.
  • liveBroadcastContent: This represents the live broadcast information, if any, which exists for a video.

Rendering the YouTube search results

We have created a separate jQuery template to represent individual search results. Once the markup is ready to be rendered, we place the markup in a video container. For this, we have added an additional row in our page layout. The following code shows the additional row markup to render YouTube-related results in the page:

<div class="row youtube-video-container hide"> <div class="page-header text-default"> <h2>YouTube Related Search Video</h2> </div> <div class="col-sm-6"> <ul class="media-list ts-video-container"></ul> </div> <div class="col-sm-6"> <!--Space for Embedding video--> </div> </div>

The following code has the jQuery template to represent each video result in the list:

<script id="aVideoTemplate" type="text/x-jquery-tmpl"> <li class="media btn-link youtube-video" data-videoId=
"${id.videoId}"> <a class="pull-left" href="#"> <img class="media-object" src ="${snippet.thumbnails.default.url}"
alt="${snippet.title}
"> </a> <div class="media-body"> <h4 class="media-heading">${snippet.title}</h4> ${snippet.description} </div> </li> </script>

The following screenshot shows YouTube's response rendered at the top of the page. The search keyword is Cassandra Administration for a q parameter value. It returns five results per page. We have only rendered the first page as an unordered elements list.

The jQuery code that implemented this search is listed in the following code:

/*Returns a jQuery Promise Object For YouTube Search*/ doYouTubeSearch : function(searchKeyWord){ var baseUrl ="https://www.googleapis.com/youtube/v3/search", searchRequest = $.ajax({url:baseUrl, data:{ q: searchKeyWord, part:"snippet", key :"AIzaSyBTYn7fvH1mpIKlw8W5K4Ju-hNaievd9Fs" } }); return searchRequest.promise(); }, /*Event Listener for click event YouTube search button*/ initYouTubeButton : function(){ $('.packt-app').on('click',' button.packt-youtube-button',function(e){ var title = $(e.target).attr('data-bookTitle'), promisedData = PACKT_PRODUCT_APP.doYouTubeSearch(title); promisedData.done(function(data){ /*By Default, Initial result returns only 5 video, *other related video can be called using *Pagination info returned in the response */ var videoItemArray = data.items; PACKT_PRODUCT_APP.doVideoRendering(videoItemArray); }); }); }, /*jQuery Template building with JSON data*/ doVideoRendering: function(data){ var videoItemContainer =$('.ts-video-container'), aVideoTemplate = $('#aVideoTemplate').tmpl( data ),
promiseOldPro = $(videoItemContainer).find('.panel').fadeOut().
promise(); $.when(promiseOldPro).then(function(){ $('.youtube-video-container').removeClass('hide'); videoItemContainer.html(aVideoTemplate); }); }

The Firebug inspection shows the following markup generated in the container:

Embedding a YouTube video

There are different approaches to embed a YouTube video in an HTML page. YouTube provides two different APIs to embed a video to a page: the JavaScript API and IFrame API. In this section, we have used the IFrame API in order to embed the video in our page. To use this API, we need to include the iframe_api API provided by YouTube. The script code to include this API in our page is as follows:

<script src ="https://www.youtube.com/iframe_api"></script>

We have added iframe in the container. When we click on one of the search results, it receives the video ID and renders it on IFrame as a video. The jQuery code performing this is listed as follows:

initVideoPlay: function(){ $('.packt-app').on('click',' li.youtube-video',function(e){ var videoId = $(e.currentTarget).attr('data-videoId'), embedURL= "https://www.youtube.com/embed/"+videoId; $('iframe#ytplayer').attr('src',embedURL); }); }

The embedded URL has the format https://www.youtube.com/embed/<videoId>. IFrame takes this URL to render the video player of YouTube. We have added an IFrame in the layout and kept it hidden initially. The following code shows the IFrame embedded in the markup:

<div class="row youtube-video-container hide"> <div class="page-header text-default"> <h2>YouTube Related Search Video</h2> </div> <div class="col-sm-6"> <ul class="media-list ts-video-container"></ul> </div> <div class="col-sm-6"> <iframe id="ytplayer" type="text/html" width="100%" height="300"
src ="" frameborder="0" allowfullscreen></iframe>
</div> </div>

In the preceding code, the width of the IFrame is 100 percent. So, it will be a fluid layout on the available size of the container. The following screenshot shows the video player loaded with the target video on clicking the first item from the list of video links:

The HTML markup for the IFrame video player in Firebug looks like the following screenshot:

After the integration of the video search feature of YouTube, the changed page will look like the following screenshot:

Summary

In this article, we have learned about the YouTube API. We have seen how to create a Google client API to use the YouTube data. We have also seen how to use jQuery AJAX and promise to make a request to YouTube videos. Also, we have explored the YouTube provided IFrame API to embed videos in our page.

Resources for Article:


Further resources on this subject:


Books to Consider

comments powered by Disqus
X

An Introduction to 3D Printing

Explore the future of manufacturing and design  - read our guide to 3d printing for free