How to Discover Playlist IDs with the YouTube Data API

JS Bin on jsbin.com

Editor's Note: The interactive window above is an embedded "Bin," the canonical version of which can be found o JSBin. It offers you the ability to experiment with the sample code in place (no need to cut and paste it to your own environment). You can change the HTML, the CSS, and/or the Javascript and any changes you make will be reflected in the Output pane on the right hand side (the resulting web page). Go ahead and play with it! You can't hurt it. Try resizing the panes by clicking and dragging their vertical borders. If you click the JSBin button in the top left hand corner, it will give you the ability to edit the Bin over on JSBin.com. If you click the Save button next to it, it will give you the opportunity to clone the same Bin under your own JSBin account. Whether you're working in the embedded version or on JSBin's site, you can view the Bin's Console. There are five buttons at the top-center of the interactive window above. Each button toggles the corresponding pane on and off. Note that this feature may not work 100% in some browser's private browser windows.

This is the second part of our series on How to Develop With the YouTube Data API. In part one we showed you how to build an app that returns the contents of a publicly viewable YouTube playlist.

In our previous tutorial, we showed you how to work with the YouTube Data APITrack this API to get the contents of a YouTube channel's playlist. In order to keep the code simple, we assumed that you already had the ID of the playlist you want to retrieve. In this tutorial we'll explain how you can show all of a channel's playlists programmatically by only knowing the channel ID. So, essentially, we'll be querying the YouTube Data API with nothing but the channel ID in order to discover all the playlist IDs. Then, we'll query the YouTube Data API with each of those playlist IDs to retrieve and list their contents in our Web app.

In the original code, once the user has submitted their API key and clicked the Show Play List button, we called the /playlistItems resource using the assumption that the user already knows the ID of the playlist ID they wish to display. The result looked like the snippet below

 $(document).ready(function(){
               getVids("Karaoke Play List", "PLfHByg2esTuIuuHC2rLY7aCCP0yKn9622"); 
     });                  
  
  function getVids(playListTitle,playListID) {
    $.get(
      "https://www.googleapis.com/youtube/v3/playlistItems", {
        part: "snippet",
        maxResults: 20,
        playlistId: playListID,
        key: localStorage.getItem("storedApiKey") },

We called /playlistItems and passed in the hardcoded playlistId (here the ID is PLfHByg2esTuIuuHC2rLY7aCCP0yKn9622) which allowed us to center in on the playlist we want. When calling /playlistItems, we identified the part we wanted returned as the "snippet." The Data API reference shows what the full JSON structure of the playList Items resource looks like. The "snippet" portion of that resource looks like this:

"snippet": {
    "publishedAt": datetime,
    "channelId": string,
    "title": string,
    "description": string,
    "thumbnails": {
      (key): {
        "url": string,
        "width": unsigned integer,
        "height": unsigned integer
      }
    },
    "channelTitle": string,
    "playlistId": string,
    "position": unsigned integer,
    "resourceId": {
      "kind": string,
      "videoId": string,
    }
  },

You can see that both the title and the videoId are available and both were used in part 1 of this tutorial series to create the display of songs in the playlist.

For the first tutorial we could have avoided building the getVids subroutine, but we knew that for this second tutorial that we wanted the code to cycle through all the playlists associated with a YouTube channel so that, in turn, we could call the getVids routine for each of those playlists. Now for this second tutorial we want to take the next step. We're going to assume that you have the channel ID and from that we'll show you how to get the playlist ID programmatically.

The first thing you need to do is get the channel ID for the YouTube channel that you want to work with. You can do this by hacking the URL of the channel as shown in the video below.

With the channel ID in hand, we can start extending our code from part one. In order to get a list of the playlists IDs associated with our channel we need to make a call to the API's /playlists resource.

$.get("https://www.googleapis.com/youtube/v3/playlists", {            
    'part': 'snippet, id',                                            
            'channelId' : localChannelId,
    'key': localStorage.getItem("storedApiKey") },

The /playlists resource does not accept YouTube username as a parameter which is why we had to go through the step of hacking the channel URL. Once we have the playlists IDs, we can use the getVids subroutine from part one to cycle through the playlists and display the songs within each.

$.get("https://www.googleapis.com/youtube/v3/playlists", {            
    'part': 'snippet, id',                                        
    'channelId' : localChannelId,
    'key': localStorage.getItem("storedApiKey") },
    function(data) {                                              
        $.each(data.items, function(i, item) { 
            getVids(item.snippet.title, item.id);                           
        });
    }     
); 

As a final touch we can build a linked header that displays the channel name above the playlists and link to the channel home page. For this part, it is assumed that you already have both the channel name and channel ID so the code for this is simply a matter of building out the link using the two defined variables.

document.getElementById("div2").innerHTML =                           
"<h1>YouTube Channel: <a href='http://www.youtube.com/channel/"    
+ localChannelId + "' target = '_newtab'<"                          
+ youTubeUserName + "</a></h1>";

When put all together, you now have the ability to take the channel ID for a YouTube user and query the API to get a listing of that user's playlists. This extends the functionality of our code but you are still required to know the channel ID ahead of time. In the next part, we will show you how to get a listing of a user's playlists by only needing to know a YouTube user's username.

This is the second part of our series on How to Develop With the YouTube Data API. In part three we show you how to get a listing of a YouTube user's playlists by only needing to know a YouTube username.

Be sure to read the next Application Development article: How to Discover Channel IDs with the YouTube Data API

 

Comments (0)