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. This article demonstrates how you can retrieve information of a YouTube video (e.g. title, description, thumbnail, duration, views and rating) using the YouTube Data API and jQuery.

Starting from version 3, YouTube data API requires an application key and billing information just like Google maps. However, the API offers few million requests free each day. Authentication is not required for most read-only operations.

Retrieving the Video Feed

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

https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=VIDEO_ID

The above URL returns the following JSON output:

{
 "kind": "youtube#videoListResponse",
 "etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/OqDg_wlZW5TqOuZ3qa7B7MfQFEE\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#video",
   "etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/D28zDa764mIZZdUYCoxPYq9Yp_s\"",
   "id": "gzDS-Kfd5XQ",
   "snippet": {
    "publishedAt": "2008-08-06T18:56:56.000Z",
    "channelId": "UCoookXUzPciGrEZEXmh4Jjg",
    "title": "Sesame Street: Ray Charles Sings \"I Got A Song\"  With Bert & Ernie",
    "description": "For more videos and games check out our new website at http://www.sesamestreet.org \n\nIn this video, Bert and Ernie perform with Ray Charles. \n\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.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/gzDS-Kfd5XQ/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/gzDS-Kfd5XQ/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/gzDS-Kfd5XQ/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "Sesame Street",
    "categoryId": "24",
    "liveBroadcastContent": "none"
   }
  }
 ]
}

jQuery Example

The following demo fetches the video information via AJAX. It uses jQuery.getJSON function to retrieve data from YouTube API. The code requests snippet and statistics "parts" of video data.

References