Extracting The Latest Video From YouTube’s Data API

Here’s a simple function demonstrating how to access the YouTube Data API. This code extracts the title and URL of the latest video uploaded by a given user, then records the information to logs.

The title and URL of the video are contained in the variables video_title and video_url . This code snippet pulls the latest video uploaded by the user TEDtalksDirector – this can be changed by editing the url variable.

/**
 * In this method, we'll pull the latest video uploaded 
 * from a specific user.
 * 
 * @throws IOException May be thrown by the low-level URLFetch service.
 */
public void getYouTubeVideo() {
    try {
        //This is the API url for videos uploaded by the user TEDtalksDirector
        URL url = new URL("http://gdata.youtube.com/feeds/api/users/TEDtalksDirector/uploads?prettyprint=true&v=2&alt=jsonc");
        //Have the URLFetch library grab the contents of the URL.
        HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(url);
        String response_contents = new String(response.getContent());
        //If the response was successful, process the returned JSON.
        //This line goes through the JSON tree to find and retrieve 
        //the JSON object representing the last uploaded video.
        JSONArray video_list = (new JSONObject(response_contents)).getJSONObject("data").getJSONArray("items");
        JSONObject latest_video = video_list.getJSONObject(0);
        //Pull out the video title and url.
        String video_title = latest_video.getString("title");
        String video_url = latest_video.getJSONObject("player").getString("default");
        System.out.println("Latest YouTube Video Title: " + video_title + " URL: " + video_url);
    }//end try 
    catch (IOException e) {
        System.err.println("IOException while retrieving YouTube data: " + e.getMessage());
    }
    catch (JSONException e) {
        System.err.println("JSONException while parsing YouTube response: " + e.getMessage());
    }
}//end getYouTubeVideo()

To use this code, you’ll need to add in the org.json library and import the following packages:

import java.net.URL;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import org.json.*;
import java.io.IOException;