January 20, 2010

Retrieve Title, Description and Thumbnail of a YouTube Video Using JavaScript and AJAX

The YouTube Data API allows an application to interact with YouTube and perform a variety of operations; such as searching for videos, retrieve video information and upload a video on behalf of a user. The API also provides programmatic access to the video and user information stored on YouTube. Majority of data access operations are read-only and therefore do not require the YouTube API developer key.

The API is based on the Google Data Protocol which means that the data can be retrieved in ATOM/JSON format. The following example demonstrates how we can retrieve video information of a YouTube video (e.g. title, description, thumbnail, duration, author, views and rating) using the YouTube Data API, JavaScript, JSON and AJAX.

Retrieving the Video Feed

To retrieve video information from YouTube, use the following url:

http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback
  • gzDS-Kfd5XQ is the video id.
  • v=2 instructs the server to use version 2 of the API to handle this request.
  • alt=json-in-script instructs the server to send the data in JSON format wrapped inside a call to the callback function; this method is used to avoid crossdomain restrictions imposed by modern browsers.
  • callback=youtubeFeedCallback is the name of the callback function that will handle the JSON data.
  • prettyprint=true is an optional parameter that instructs the server to format the results for readability.

The above URL generates the following output (pretty printed for your convenience):

youtubeFeedCallback({
 "version": "1.0",
 "encoding": "UTF-8",
 "entry": {
  "xmlns": "http://www.w3.org/2005/Atom",
  "xmlns$media": "http://search.yahoo.com/mrss/",
  "xmlns$gd": "http://schemas.google.com/g/2005",
  "xmlns$yt": "http://gdata.youtube.com/schemas/2007",
  "gd$etag": "W/\"Dk8BQn47eCp7I2A9WhJQEU0.\"",
  "id": {
   "$t": "tag:youtube.com,2008:video:gzDS-Kfd5XQ"
  },
  "published": {
   "$t": "2008-08-06T18:56:56.000Z"
  },
  "updated": {
   "$t": "2012-07-24T04:40:53.000Z"
  },
  "category": [
   {
    "scheme": "http://schemas.google.com/g/2005#kind",
    "term": "http://gdata.youtube.com/schemas/2007#video"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/categories.cat",
    "term": "Entertainment",
    "label": "Entertainment"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "sesame"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "street"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "celebrity"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "ray"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "charles"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "ernie"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "bert"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "muppet"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "instruments"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "guitar"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "drums"
   },
   {
    "scheme": "http://gdata.youtube.com/schemas/2007/keywords.cat",
    "term": "piano"
   }
  ],
  "title": {
   "$t": "Sesame Street: Ray Charles Sings \"I Got A Song\"  With Bert & Ernie"
  },
  "content": {
   "type": "application/x-shockwave-flash",
   "src": "http://www.youtube.com/v/gzDS-Kfd5XQ?version=3&f=videos&app=youtube_gdata"
  },
  "link": [
   {
    "rel": "alternate",
    "type": "text/html",
    "href": "http://www.youtube.com/watch?v=gzDS-Kfd5XQ&feature=youtube_gdata"
   },
   {
    "rel": "http://gdata.youtube.com/schemas/2007#video.related",
    "type": "application/atom+xml",
    "href": "http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ/related?v=2"
   },
   {
    "rel": "http://gdata.youtube.com/schemas/2007#mobile",
    "type": "text/html",
    "href": "http://m.youtube.com/details?v=gzDS-Kfd5XQ"
   },
   {
    "rel": "http://gdata.youtube.com/schemas/2007#uploader",
    "type": "application/atom+xml",
    "href": "http://gdata.youtube.com/feeds/api/users/oookXUzPciGrEZEXmh4Jjg?v=2"
   },
   {
    "rel": "self",
    "type": "application/atom+xml",
    "href": "http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2"
   }
  ],
  "author": [
   {
    "name": {
     "$t": "SesameStreet"
    },
    "uri": {
     "$t": "http://gdata.youtube.com/feeds/api/users/SesameStreet"
    },
    "yt$userId": {
     "$t": "oookXUzPciGrEZEXmh4Jjg"
    }
   }
  ],
  "yt$accessControl": [
   {
    "action": "comment",
    "permission": "allowed"
   },
   {
    "action": "commentVote",
    "permission": "allowed"
   },
   {
    "action": "videoRespond",
    "permission": "denied"
   },
   {
    "action": "rate",
    "permission": "allowed"
   },
   {
    "action": "embed",
    "permission": "allowed"
   },
   {
    "action": "list",
    "permission": "allowed"
   },
   {
    "action": "autoPlay",
    "permission": "allowed"
   },
   {
    "action": "syndicate",
    "permission": "allowed"
   }
  ],
  "gd$comments": {
   "gd$feedLink": {
    "rel": "http://gdata.youtube.com/schemas/2007#comments",
    "href": "http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ/comments?v=2",
    "countHint": 311
   }
  },
  "yt$location": {
   "$t": "undefined"
  },
  "media$group": {
   "media$category": [
    {
     "$t": "Entertainment",
     "label": "Entertainment",
     "scheme": "http://gdata.youtube.com/schemas/2007/categories.cat"
    }
   ],
   "media$content": [
    {
     "url": "http://www.youtube.com/v/gzDS-Kfd5XQ?version=3&f=videos&app=youtube_gdata",
     "type": "application/x-shockwave-flash",
     "medium": "video",
     "isDefault": "true",
     "expression": "full",
     "duration": 129,
     "yt$format": 5
    },
    {
     "url": "rtsp://v5.cache2.c.youtube.com/CiILENy73wIaGQl05d2n-NIwgxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp",
     "type": "video/3gpp",
     "medium": "video",
     "expression": "full",
     "duration": 129,
     "yt$format": 1
    },
    {
     "url": "rtsp://v7.cache7.c.youtube.com/CiILENy73wIaGQl05d2n-NIwgxMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp",
     "type": "video/3gpp",
     "medium": "video",
     "expression": "full",
     "duration": 129,
     "yt$format": 6
    }
   ],
   "media$credit": [
    {
     "$t": "sesamestreet",
     "role": "uploader",
     "scheme": "urn:youtube",
     "yt$display": "SesameStreet",
     "yt$type": "partner"
    }
   ],
   "media$description": {
    "$t": "For more videos and games check out our new website at http://www.sesamestreet.org \r\n\r\nIn this video, Bert and Ernie perform with Ray Charles. \r\n\r\nSesame Street is a production of Sesame Workshop, a nonprofit educational organization which also produces Pinky Dinky Doo, The Electric Company, and other programs for children around the world.",
    "type": "plain"
   },
   "media$keywords": {
    "$t": "sesame, street, celebrity, ray, charles, ernie, bert, muppet, instruments, guitar, drums, piano"
   },
   "media$license": {
    "$t": "youtube",
    "type": "text/html",
    "href": "http://www.youtube.com/t/terms"
   },
   "media$player": {
    "url": "http://www.youtube.com/watch?v=gzDS-Kfd5XQ&feature=youtube_gdata_player"
   },
   "media$thumbnail": [
    {
     "url": "http://i.ytimg.com/vi/gzDS-Kfd5XQ/default.jpg",
     "height": 90,
     "width": 120,
     "time": "00:01:04.500",
     "yt$name": "default"
    },
    {
     "url": "http://i.ytimg.com/vi/gzDS-Kfd5XQ/mqdefault.jpg",
     "height": 180,
     "width": 320,
     "yt$name": "mqdefault"
    },
    {
     "url": "http://i.ytimg.com/vi/gzDS-Kfd5XQ/hqdefault.jpg",
     "height": 360,
     "width": 480,
     "yt$name": "hqdefault"
    },
    {
     "url": "http://i.ytimg.com/vi/gzDS-Kfd5XQ/1.jpg",
     "height": 90,
     "width": 120,
     "time": "00:00:32.250",
     "yt$name": "start"
    },
    {
     "url": "http://i.ytimg.com/vi/gzDS-Kfd5XQ/2.jpg",
     "height": 90,
     "width": 120,
     "time": "00:01:04.500",
     "yt$name": "middle"
    },
    {
     "url": "http://i.ytimg.com/vi/gzDS-Kfd5XQ/3.jpg",
     "height": 90,
     "width": 120,
     "time": "00:01:36.750",
     "yt$name": "end"
    }
   ],
   "media$title": {
    "$t": "Sesame Street: Ray Charles Sings \"I Got A Song\"  With Bert & Ernie",
    "type": "plain"
   },
   "yt$duration": {
    "seconds": "129"
   },
   "yt$uploaded": {
    "$t": "2008-08-06T18:56:56.000Z"
   },
   "yt$uploaderId": {
    "$t": "UCoookXUzPciGrEZEXmh4Jjg"
   },
   "yt$videoid": {
    "$t": "gzDS-Kfd5XQ"
   }
  },
  "gd$rating": {
   "average": 4.9510703,
   "max": 5,
   "min": 1,
   "numRaters": 981,
   "rel": "http://schemas.google.com/g/2005#overall"
  },
  "yt$statistics": {
   "favoriteCount": "2183",
   "viewCount": "756330"
  },
  "yt$rating": {
   "numDislikes": "12",
   "numLikes": "969"
  }
 }
}
);

JavaScript Example

Given the above information, retrieving and displaying the video information via JavaScript is fairly straight-forward, as shown in the example below:

<script type="text/javascript">
  function youtubeFeedCallback(data) {
    var s = '';
    s += '<img src="' + data.entry.media$group.media$thumbnail[0].url + '" width="' + data.entry.media$group.media$thumbnail[0].width + '" height="' + data.entry.media$group.media$thumbnail[0].height + '" alt="' + data.entry.media$group.media$thumbnail[0].yt$name + '" align="right"/>';
    s += '<b>Title:</b> ' + data.entry.title.$t + '<br/>';
    s += '<b>Author:</b> ' + data.entry.author[0].name.$t + '<br/>';
    s += '<b>Published:</b> ' + new Date(data.entry.published.$t).toLocaleDateString() + '<br/>';
    s += '<b>Duration:</b> ' + Math.floor(data.entry.media$group.yt$duration.seconds / 60) + ':' + (data.entry.media$group.yt$duration.seconds % 60) + ' (' + data.entry.media$group.yt$duration.seconds + ' seconds)<br/>';
    if (data.entry.gd$rating) {
      s += '<b>Rating:</b> ' + data.entry.gd$rating.average.toFixed(1) + ' out of ' + data.entry.gd$rating.max + ' (' + data.entry.gd$rating.numRaters + ' ratings)<br/>';
    }
    s += '<b>Statistics:</b> ' + data.entry.yt$statistics.favoriteCount + ' favorite(s); ' + data.entry.yt$statistics.viewCount + ' view(s)<br/>';
    s += '<br/>' + data.entry.media$group.media$description.$t.replace(/\n/g, '<br/>') + '<br/>';
    s += '<br/><a href="' + data.entry.media$group.media$player.url + '" target="_blank">Watch on YouTube</a>';
    document.write(s);
  }
</script>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&amp;alt=json-in-script&amp;callback=youtubeFeedCallback"></script>

Output

AJAX Example

The following demo fetches the video information via AJAX. It uses jQuery.getScript function to retrieve the data asynchronously. View the page source to inspect the code.

Enter YouTube Video ID or URL in the text box below

Video information will appear here.

References