Search code examples
c#.netyoutubeyoutube-api

Get youtube playlist by ID in YouTube API .net


I am trying to download the most recent items from a YouTube playlist in a C# .NET program. Right now I have a program that successfully gets the necessary data from my channel's Uploads playlist using channel.ContentDetails.RelatedPlaylists.Uploads;, which I got from the sample program on the API page. But I can't find any information in the API docs about how to switch that line or lines around it to get a playlist by ID rather than my own uploads.

This is not a duplicate because other examples on this page explain how to find it through an http link, as in <a href ='http://gdata.youtube.com/feeds/api/playlists/... etc. I want to do it directly through the API's methods. The part of my code that downloads the data is included below.

private async Task Run()
{
    var youtubeService = new YouTubeService(new BaseClientService.Initializer()
    {
        ApiKey = "API KEY HERE",
        ApplicationName = this.GetType().ToString()
    });

    //MAYBE I NEED TO CHANGE THIS? SOMETHING LIKE
    //'youtubeservice.Playlists.IDUNNOWHAT'
    var channelsListRequest = youtubeService.Channels.List("contentDetails");
    channelsListRequest.Id = "CHANNEL ID HERE";
    
    // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
    var channelsListResponse = await channelsListRequest.ExecuteAsync();
    foreach (var channel in channelsListResponse.Items)
    {


        //OR MAYBE I NEED TO CHANGE THIS PART? 
        //LIKE 'channel.ContentDetails.SOMETHING
        var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;


        var nextPageToken = "";
        while (nextPageToken != null)
        {
            var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
            playlistItemsListRequest.PlaylistId = uploadsListId;
            playlistItemsListRequest.MaxResults = 50;
            playlistItemsListRequest.PageToken = nextPageToken;

            // Retrieve the list of videos uploaded to the authenticated user's channel.
            var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
            /*
            * DO A BUNCH OF STUFF WITH THE YOUTUBE DATA
            */
            nextPageToken = playlistItemsListResponse.NextPageToken;
        }
    }
}

Solution

  • In the documentation, it lists the playlists you can get by using ContentDetails.RelatedPlaylists:

    • likes
    • favorites
    • uploads
    • watchHistory
    • watchLater

    Therefore, if you want to get the items for a playlist you created you won't be able to do it using ContentDetails.RelatedPlaylists, you'll have to provide the playlist ID. I believe it should work with the code you provided (might need a few tweaks) if you change

    playlistItemsListRequest.PlaylistId = uploadsListId;
    

    to use the ID of the playlist whose videos you want to get.