309

We need a video list by channel name of YouTube (using the API).

We can get a channel list (only channel name) by using the below API:

https://gdata.youtube.com/feeds/api/channels?v=2&q=tendulkar

Below is a direct link of channels

https://www.youtube.com/channel/UCqAEtEr0A0Eo2IVcuWBfB9g

Or

WWW.YouTube.com/channel/HC-8jgBP-4rlI

Now, we need videos of channel >> UCqAEtEr0A0Eo2IVcuWBfB9g or HC-8jgBP-4rlI.

We tried

https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&User=UC7Xayrf2k0NZiz3S04WuDNQ https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&q=UC7Xayrf2k0NZiz3S04WuDNQ

But, it does not help.

We need all the videos posted on the channel. Videos uploaded to a channel can be from multiple users thus I don't think providing a user parameter would help...

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Rajendra Dewani
  • 3,281
  • 3
  • 15
  • 8

20 Answers20

297

You need to look at the YouTube Data API. You will find there documentation about how the API can be accessed. You can also find client libraries.

You could also make the requests yourself. Here is an example URL that retrieves the latest videos from a channel:

https://www.googleapis.com/youtube/v3/search?key={your_key_here}&channelId={channel_id_here}&part=snippet,id&order=date&maxResults=20

After that you will receive a JSON with video ids and details, and you can construct your video URL like this:

http://www.youtube.com/watch?v={video_id_here}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
akshay
  • 5,811
  • 5
  • 39
  • 58
  • 45
    This will only return the first `maxResults=20` (up to 50) videos, but not the entire channel catalogue. If you want more results, use the pageToken as described [here](https://developers.google.com/youtube/v3/docs/search/list). – Fábio Perez Aug 14 '14 at 15:12
  • I don't find where the requested feature is written in document. Videos have only three filters and none of them relate to channel. – Romulus Urakagi Ts'ai Nov 19 '14 at 06:50
  • 3
    Romulus Urakagi Ts'ai: while requesting videos you are giving channelId, that is the filter for channel. – akshay Nov 19 '14 at 08:36
  • 16
    Worth noting you can only get up to 500 videos from a channel using the next page tokens. – Tony Paternite Aug 30 '16 at 01:21
  • Using the browser Key will save you tie in android too and create your own HTTP CLIENT LIKE Retrofit to fetch data – Goodlife Aug 30 '16 at 08:23
  • 4
    @TonyPaternite How do I get more than 500 videos. I am currently facing this issue. – Raja Oct 23 '16 at 01:53
  • 3
    The issue is explained well here. https://code.google.com/p/gdata-issues/issues/detail?id=4282 Trying with a different range of dates is one way to get more videos it seems. – Raja Oct 23 '16 at 02:06
  • 1
    @Raja Yeah, I would try that option with the date range. The API doesn't allow more than 500 results from a channel. – Tony Paternite Oct 25 '16 at 18:28
  • 1
    May I ask what `?key={your_key_here}` needs, specifically, what is: `your_key_here`? How can I get that? – hello_there_andy Jan 23 '17 at 18:49
  • 3
    @hello_there_andy : You need a Google Account to access the Google Developers Console, request an API key, and register your application. For more info, please check : https://developers.google.com/youtube/v3/getting-started – akshay Jan 24 '17 at 09:35
  • this also includes the channel item. for me it works adding also type=video – mwm Sep 15 '17 at 16:31
  • You can try the api here : https://developers.google.com/apis-explorer/#search/youtube/youtube/v3/youtube.search.list (apis-exporer - > youtube data api -> search.list ), don't forget to set the parameter type to "video". – Adrien H Mar 12 '18 at 10:44
  • 24
    beware of using search as it has a quote cost of 100! – CMash Aug 08 '19 at 15:55
  • @CMash This is the issue that I'm encountering. You run through your quota very fast. – Berry Blue Dec 07 '19 at 22:56
  • 9
    Please note: the `search` operation is very expensive (100 quota) compared to the operations suggested by [jambrose](https://stackoverflow.com/a/27872244/2807296) (3 + 5 quota) (as of march 2020). See [Quota Calculator](https://developers.google.com/youtube/v3/determine_quota_cost). – Teemoh Mar 27 '20 at 04:57
  • it may miss some videos! Instead, use "uploads" playlist as described below https://stackoverflow.com/a/27872244/2154075 – IvanM Jul 03 '20 at 09:49
  • I tried this but it failed with a quota exceeded error, even the only thing I've done with my quota is tried this query and got that error - it's a brand new project. Anything about this that could have caused that? – Duncan Marshall Apr 18 '21 at 16:41
232

First, you need to get the ID of the playlist that represents the uploads from the user/channel:

https://developers.google.com/youtube/v3/docs/channels/list#try-it

You can specify the username with the forUsername={username} param, or specify mine=true to get your own (you need to authenticate first). Include part=contentDetails to see the playlists.

GET https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=jambrose42&key={YOUR_API_KEY}

In the result "relatedPlaylists" will include "likes" and "uploads" playlists. Grab that "upload" playlist ID.

Also note the upload playlist id is your channelId prefixed with UU instead of UC.

Next, get a list of videos in that playlist:

https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it

Just drop in the playlistId!

GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId=UUpRmvjdu3ixew5ahydZ67uA&key={YOUR_API_KEY}
cgenco
  • 3,370
  • 2
  • 31
  • 36
jambrose
  • 2,553
  • 1
  • 13
  • 9
  • 1
    Not everyone has a youtube username in this brand new world. Some of them only have a google+ user id number, which doesn't work in the place of a youtube username – kristopolous Mar 22 '16 at 23:33
  • 1
    @kristopolous Every YouTube channel has a channel ID. If you go to a YouTube page via Google plus, it uses the Google plus user id as the link to the channel. If you went to the channel from a YouTube video, it uses YouTube's channel ID property instead. – Ignat Nov 02 '16 at 01:35
  • 57
    This is perfect. Particularly because it only spends 2 quota points instead of 100 (that the *search* call would spend). – JP de la Torre Nov 12 '16 at 10:28
  • @kristopolous is correct: you can't use those channel IDs as names. – Ken Sharp Jan 09 '17 at 19:19
  • 1
    Notice that playlist items api will include unlisted and deleted videos too, but you can use search api to list public videos only by channel id – Muhammad Jan 31 '17 at 11:54
  • 2
    somteimes it(https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it) works , sometimes it throws 404 for same uploadId, don't know whats going on. – ishandutta2007 Apr 23 '17 at 07:12
  • 1
    @jambrose in the playlistItems endpoint how to use some date range parameter like publishAfter/ publishedBefore. I tried It, not working So how I fetch all the videos of a channel. – Harsh sachdev Apr 22 '19 at 07:17
  • I was scraping channel pages because search endpoint costs 100 points. Liek to say a big THANK YOU for this one. This was not obvious from the docs and it works perfectly. Also the search call doesn't necessarily return only the specified channel, and it gives up after a few 100 results. This endpoint seem to work fine. – Madushan May 18 '19 at 11:53
  • 3
    If you want to reduce quota by another 2 units, set part=snippet only. contentDetails (videoId, videoPublishedAt) can be found inside the snippet node so it's redundant. – jtubre Dec 10 '19 at 22:14
  • For those that need it - I implemented this approach, you can try it online: http://yts.sourceforge.net/getchannelvideos.html – poke May 22 '20 at 20:05
  • 3
    You can ofc use a channel ID to get this information in the first place, just specify the ``id`` parameter instead of ``forUsername``. If you're attempting to get the upload playlist for multiple channels at once like I am, you can specify multiple IDs with either a comma or using the ``id`` parameter multiple times. – TrisT Jan 04 '21 at 05:18
  • 14
    Also, one thing I noticed is that as (as far as I can see), the uploads playlist ID is the same as the channel ID with the second character from the left replaced with a U. So for instance the uploads playlist for channelID ``UC-lHJZR3Gqxm24_Vd_AJ5Yw`` would be ``UU-lHJZR3Gqxm24_Vd_AJ5Yw``. Makes sense, I assume it would stand for "user channel" and "user uploads". So if you need a few extra quota points I suppose that could be a solution. – TrisT Jan 05 '21 at 04:21
  • Is there a way to search video later than a timestamp? – ying Jan 12 '21 at 00:26
  • Can you please add the information about how to get ALL videos using this based on `pageToken` from the 2nd part,so the answer is complete for this Q. (I know how to do it, but just for others) :) – jave.web Jan 20 '21 at 16:24
  • This is exactly what I was looking for, using the "upload" playlist id is far from being intuitive. – John Funk Feb 03 '21 at 16:19
  • JFYF live videos are missing from the uploads related playlist of the channel – Tassoman Feb 17 '21 at 19:28
  • 1
    looks like this is limited up to 20k videos – teran Mar 11 '21 at 17:42
  • Its also worth saying that if the forUsername stops working - revisit the page, and see if it defaults to an ID instead. One of my forUsernames wasn't working but grabbing the ID instead did. – Antony Apr 14 '21 at 15:53
  • 1
    This does not return all channel's videos. It returns all videos in the uploads playlist, but not all channel's videos. – Ammar Alyousfi Oct 20 '21 at 14:28
  • @jambrose How can this be modified to include view count too? I can list all videos from a specific playlist but I need view count too, if I simply change part=snippet to part=snippet,statistics I then get no results. – jfar_2020 Nov 07 '21 at 11:29
  • Thank you, I have been playing around Youtube APIs for hours. It's insane that the search API does not return consistent results. Going through the uploads playlist got me ALL the videos – babgyy Dec 09 '22 at 15:55
141

Here is a video from Google Developers showing how to list all videos in a channel in v3 of the YouTube API.

There are two steps:

  1. Query Channels to get the "uploads" Id. eg https://www.googleapis.com/youtube/v3/channels?id={channel Id}&key={API key}&part=contentDetails

  2. Use this "uploads" Id to query PlaylistItems to get the list of videos. eg https://www.googleapis.com/youtube/v3/playlistItems?playlistId={"uploads" Id}&key={API key}&part=snippet&maxResults=50

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
virtualmic
  • 3,173
  • 6
  • 26
  • 34
  • 1
    Can "uploads" Id change for a given channel ? – ishandutta2007 Apr 23 '17 at 01:42
  • seems uploads are same as channelId , but terribly inconsistent APIs, can some answer this http://stackoverflow.com/questions/43568521/youtube-playlistitems-list-api-sometimes-works-sometimes-throws-404 – ishandutta2007 Apr 23 '17 at 12:57
  • 1
    @ishandutta2007 no uploads id is different from channel id. – vicke4 Apr 29 '18 at 12:57
  • @virtualmic@Peter Perfect Solution Guys , Thanks – Aaska Patel Jun 11 '19 at 06:18
  • it is working fine. but i have multiple channel ids, so how can i send them to api, can i use comma seperated channel ids – Onkar Musale Jan 01 '20 at 10:10
  • @vicke4 is correct, they are different and it looks like from the channels I deal with (quite a few) that the channels' uploads ID is the same as the Channel ID, except it starts with UU instead of UC. This may not be a certainty though, I can't find any doco about it. – Matt Booth Feb 18 '20 at 11:48
  • 2
    @MattBooth is spot on. It seems the pattern is Channel ID = UC + { User ID }, Upload Playlist ID = UU + { User ID } . I'm guessing it's auto-generated for every channel at the point of creation (or for old channels, when the switch happened from YT's API to Google's). Still can't find any source that confirms it, but through testing a few hundred channels, they were all followed this pattern. UC would make sense to denote User Channel, while UU could be User Uploads. – Scuilla Dec 15 '20 at 21:14
  • it looks like api limits to 20k videos in playlist while search with empty query returns 26k videos – teran Mar 11 '21 at 17:40
52

To get channels list :

Get Channels list by forUserName:

https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&forUsername=Apple&key=

Get channels list by channel id:

https://www.googleapis.com/youtube/v3/channels/?part=snippet,contentDetails,statistics&id=UCE_M8A5yxnLfW0KghEeajjw&key=

Get Channel sections:

https://www.googleapis.com/youtube/v3/channelSections?part=snippet,contentDetails&channelId=UCE_M8A5yxnLfW0KghEeajjw&key=

To get Playlists :

Get Playlists by Channel ID:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=

Get Playlists by Channel ID with pageToken:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=&pageToken=CDIQAA

To get PlaylistItems :

Get PlaylistItems list by PlayListId:

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,contentDetails&maxResults=25&playlistId=PLHFlHpPjgk70Yv3kxQvkDEO5n5tMQia5I&key=

To get videos :

Get videos list by video id:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw&key=

Get videos list by multiple videos id:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw,Qgy6LaO3SB0,7yPJXGO2Dcw&key=

Get comments list

Get Comment list by video ID:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&videoId=el****kQak&key=A**********k

Get Comment list by channel ID:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&channelId=U*****Q&key=AI********k

Get Comment list by allThreadsRelatedToChannelId:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&allThreadsRelatedToChannelId=UC*****ntcQ&key=AI*****k

Here all api's are Get approach.

Based on channel id we con't get all videos directly, that's the important point here.

For integration https://developers.google.com/youtube/v3/quickstart/ios?ver=swift

Naresh
  • 16,698
  • 6
  • 112
  • 113
14

Here is the code that will return all video ids under your channel

<?php 
    $baseUrl = 'https://www.googleapis.com/youtube/v3/';
    // https://developers.google.com/youtube/v3/getting-started
    $apiKey = 'API_KEY';
    // If you don't know the channel ID see below
    $channelId = 'CHANNEL_ID';

    $params = [
        'id'=> $channelId,
        'part'=> 'contentDetails',
        'key'=> $apiKey
    ];
    $url = $baseUrl . 'channels?' . http_build_query($params);
    $json = json_decode(file_get_contents($url), true);

    $playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];

    $params = [
        'part'=> 'snippet',
        'playlistId' => $playlist,
        'maxResults'=> '50',
        'key'=> $apiKey
    ];
    $url = $baseUrl . 'playlistItems?' . http_build_query($params);
    $json = json_decode(file_get_contents($url), true);

    $videos = [];
    foreach($json['items'] as $video)
        $videos[] = $video['snippet']['resourceId']['videoId'];

    while(isset($json['nextPageToken'])){
        $nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
        $json = json_decode(file_get_contents($nextUrl), true);
        foreach($json['items'] as $video)
            $videos[] = $video['snippet']['resourceId']['videoId'];
    }
    print_r($videos);

Note: You can get channel id at https://www.youtube.com/account_advanced after logged in.

Mihir Bhatt
  • 3,019
  • 2
  • 37
  • 41
13

Below is a Python alternative that does not require any special packages. By providing the channel id it returns a list of video links for that channel. Please note that you need an API Key for it to work.

import urllib
import json

def get_all_video_in_channel(channel_id):
    api_key = YOUR API KEY

    base_video_url = 'https://www.youtube.com/watch?v='
    base_search_url = 'https://www.googleapis.com/youtube/v3/search?'

    first_url = base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=25'.format(api_key, channel_id)

    video_links = []
    url = first_url
    while True:
        inp = urllib.urlopen(url)
        resp = json.load(inp)

        for i in resp['items']:
            if i['id']['kind'] == "youtube#video":
                video_links.append(base_video_url + i['id']['videoId'])

        try:
            next_page_token = resp['nextPageToken']
            url = first_url + '&pageToken={}'.format(next_page_token)
        except:
            break
    return video_links
Stian
  • 776
  • 7
  • 10
  • How does this work? I pasted the API KEY using single quotes ' ' into the api_key variable, then I called the function passing in the channel id, then ran the python program, but nothing happens. – Joffrey Baratheon Apr 27 '18 at 00:33
  • @JoffreyBaratheon the function return an array, you need to contain that to a variable. For example : `video_list = get_all_video_in_channel("ABC123EFG456")` then you could print it to see the array using `print(video_list)` – phapha pha May 03 '18 at 02:05
  • Even though this might be the quickest way, the cost of "search" is 100 unit and that may result quota exceed. – Yasin Okumuş Sep 27 '20 at 00:42
9

Short answer:

Here's a library called scrapetube That can help with that.

pip install scrapetube

import scrapetube
import simplejson as json

videos = scrapetube.get_channel("UC9-y-6csu5WGm29I7JiwpnA")

for video in videos:
    print(video['videoId'])
    print(video['title']['runs'][0]['text'])
    print(video['publishedTimeText']['simpleText'])
    print('\r\n')
    # DEBUG: print(json.dumps(video))

Long answer:

The module mentioned above was created by me due to a lack of any other solutions. Here's what i tried:

  1. Selenium. It worked but had three big drawbacks: 1. It requires a web browser and driver to be installed. 2. has big CPU and memory requirements. 3. can't handle big channels.
  2. Using youtube-dl. Like this:
import youtube_dl
    youtube_dl_options = {
        'skip_download': True,
        'ignoreerrors': True
    }
    with youtube_dl.YoutubeDL(youtube_dl_options) as ydl:
        videos = ydl.extract_info(f'https://www.youtube.com/channel/{channel_id}/videos')

This also works for small channels, but for bigger ones i would get blocked by youtube for making so many requests in such a short time (because youtube-dl downloads more info for every video in the channel).

So i made the library scrapetube which uses the web API to get all the videos.

petrosmm
  • 528
  • 9
  • 23
dermasmid
  • 428
  • 5
  • 7
8

Since everyone answering this question has problems due to the 500 video limit here's an alternate solution using youtube_dl in Python 3. Also, no API key is needed.

  1. Install youtube_dl: sudo pip3 install youtube-dl
  2. Find out your target channel's channel id. The ID is going to start with UC. Replace the C for Channel with U for Upload (i.e. UU...), this is the upload playlist.
  3. Use the playlist downloader feature from youtube-dl. Ideally you do NOT want to download every video in the playlist which is the default, but only the metadata.

Example (warning -- takes tens of minutes):

import youtube_dl, pickle

             # UCVTyTA7-g9nopHeHbeuvpRA is the channel id (1517+ videos)
PLAYLIST_ID = 'UUVTyTA7-g9nopHeHbeuvpRA'  # Late Night with Seth Meyers

with youtube_dl.YoutubeDL({'ignoreerrors': True}) as ydl:

    playd = ydl.extract_info(PLAYLIST_ID, download=False)

    with open('playlist.pickle', 'wb') as f:
        pickle.dump(playd, f, pickle.HIGHEST_PROTOCOL)

    vids = [vid for vid in playd['entries'] if 'A Closer Look' in vid['title']]
    print(sum('Trump' in vid['title'] for vid in vids), '/', len(vids))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
xjcl
  • 12,848
  • 6
  • 67
  • 89
  • 1
    I think this is the best answer since it doesn't need API key. To make it even more automated you can use `@for /f "usebackq tokens=2 delims=: " %a in (\`dl-list.py^|findstr information\`) do @echo https://www.youtube.com/watch?v=%a`. It will print all the URL of the videos. `PLAYLIST_ID` can be a playlist or channel ID. – cdlvcdlv May 26 '18 at 20:41
  • You can infer it but I forgot to say that I saved the code as `dl-list.py`. – cdlvcdlv May 26 '18 at 20:49
  • This does not work at this time. It downloads empty info. – Jeff Winchell Jun 27 '23 at 21:55
8

Thanks to the references shared here and elsewhere, I've made an online script / tool that one can use to obtain all videos of a channel.

It combines API calls to youtube.channels.list, playlistItems, videos. It uses recursive functions to make the asynchronous callbacks run the next iteration upon getting a valid response.

This also serves to limit the actual number of requests made at a time, hence keeping you safe from violating YouTube API rules. Sharing shortened snippets and then a link to the full code. I got around the 50 max results per call limitation by using the nextPageToken value that comes in the response to fetch the next 50 results and so on.

function getVideos(nextPageToken, vidsDone, params) {
    $.getJSON("https://www.googleapis.com/youtube/v3/playlistItems", {
        key: params.accessKey,
        part: "snippet",
        maxResults: 50,
        playlistId: params.playlistId,
        fields: "items(snippet(publishedAt, resourceId/videoId, title)), nextPageToken",
        pageToken: ( nextPageToken || '')
        },
        function(data) {
            // commands to process JSON variable, extract the 50 videos info

            if ( vidsDone < params.vidslimit) {

                // Recursive: the function is calling itself if
                // all videos haven't been loaded yet
                getVideos( data.nextPageToken, vidsDone, params);

            }
             else {
                 // Closing actions to do once we have listed the videos needed.
             }
    });
}

This got a basic listing of the videos, including id, title, date of publishing and similar. But to get more detail of each video like view counts and likes, one has to make API calls to videos.

// Looping through an array of video id's
function fetchViddetails(i) {
    $.getJSON("https://www.googleapis.com/youtube/v3/videos", {
        key: document.getElementById("accesskey").value,
        part: "snippet,statistics",
        id: vidsList[i]
        }, function(data) {

            // Commands to process JSON variable, extract the video
            // information and push it to a global array
            if (i < vidsList.length - 1) {
                fetchViddetails(i+1) // Recursive: calls itself if the
                                     //            list isn't over.
            }
});

See the full code here, and live version here. (Edit: fixed github link)
Edit: Dependencies: JQuery, Papa.parse

Nikhil VJ
  • 5,630
  • 7
  • 34
  • 55
  • 1
    Are you sure that this works? The GitHub page is gone and then when I input API Key and channel id into the fields, I get errors. – Joffrey Baratheon Apr 27 '18 at 00:58
  • @JoffreyBaratheon thanks for pointing out the broken github link. I just ran it.. it works. Getting that playlist id is tricky.. pls see this: https://github.com/answerquest/answerquest.github.io/issues/2 – Nikhil VJ Apr 27 '18 at 14:35
  • nice job. works very well with the updated github link. you will need jquery and papaparse.min.js – Jan Bludau May 09 '19 at 05:57
  • @thE_iNviNciblE thanks for bringing that up. made a mention of it. – Nikhil VJ May 09 '19 at 15:46
  • @nikhil-vj it's not useable for a real world szenario, you shouldn't give the Client Browser the youtube API-Token. But for programming education quite nice job :-) – Jan Bludau May 11 '19 at 03:06
  • @thE_iNviNciblE that's why I let the user put in their own token :P . But API tokens are used all over the net; one can put url restrictions IP restrictions etc at the token management side so even if people take it they can't use it at their end. We can dispose tokens and make new ones quickly. It's not trivial, but not too critical of a threat either. – Nikhil VJ May 12 '19 at 05:28
  • nice recursion! – petrosmm Sep 29 '22 at 15:01
7

Try with like the following. It may help you.

https://gdata.youtube.com/feeds/api/videos?author=cnn&v=2&orderby=updated&alt=jsonc&q=news

Here author as you can specify your channel name and "q" as you can give your search key word.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nagaraja
  • 581
  • 1
  • 4
  • 12
6

Just in three steps:

  1. Subscriptions: list -> https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&maxResults=50&mine=true&access_token={oauth_token}

  2. Channels: list -> https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id={channel_id}&key={YOUR_API_KEY}

  3. PlaylistItems: list -> https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={playlist_id}&key={YOUR_API_KEY}

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sacred0x01
  • 382
  • 2
  • 11
3

Recently I had to retrieve all videos from a channel, and according to YouTube developer documentation: https://developers.google.com/youtube/v3/docs/playlistItems/list

function playlistItemsListByPlaylistId($service, $part, $params) {
    $params = array_filter($params);
    $response = $service->playlistItems->listPlaylistItems(
        $part,
        $params
    );

    print_r($response);
}

playlistItemsListByPlaylistId($service,
    'snippet,contentDetails',
    array('maxResults' => 25, 'playlistId' => 'id of "uploads" playlist'));

Where $service is your Google_Service_YouTube object.

So you have to fetch information from the channel to retrieve the "uploads" playlist that actually has all the videos uploaded by the channel: https://developers.google.com/youtube/v3/docs/channels/list

If new with this API, I highly recommend to turn the code sample from the default snippet to the full sample.

So the basic code to retrieve all videos from a channel can be:

class YouTube
{
    const       DEV_KEY = 'YOUR_DEVELOPPER_KEY';
    private     $client;
    private     $youtube;
    private     $lastChannel;

    public function __construct()
    {
        $this->client = new Google_Client();
        $this->client->setDeveloperKey(self::DEV_KEY);
        $this->youtube = new Google_Service_YouTube($this->client);
        $this->lastChannel = false;
    }

    public function getChannelInfoFromName($channel_name)
    {
        if ($this->lastChannel && $this->lastChannel['modelData']['items'][0]['snippet']['title'] == $channel_name)
        {
            return $this->lastChannel;
        }
        $this->lastChannel = $this->youtube->channels->listChannels('snippet, contentDetails, statistics', array(
            'forUsername' => $channel_name,
        ));
        return ($this->lastChannel);
    }

    public function getVideosFromChannelName($channel_name, $max_result = 5)
    {
        $this->getChannelInfoFromName($channel_name);
        $params = [
            'playlistId' => $this->lastChannel['modelData']['items'][0]['contentDetails']['relatedPlaylists']['uploads'],
            'maxResults'=> $max_result,
        ];
        return ($this->youtube->playlistItems->listPlaylistItems('snippet,contentDetails', $params));
    }
}

$yt = new YouTube();
echo '<pre>' . print_r($yt->getVideosFromChannelName('CHANNEL_NAME'), true) . '</pre>';
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Glastis
  • 163
  • 4
  • 15
  • Does this get all the videos with titles, URL of the video, an image identifying the video, number of likes/comments? Some info on how this publishes would be helpful. Thanks. – Khom Nazid Jun 07 '19 at 23:23
2

Using API version 2, which is deprecated, the URL for uploads (of channel UCqAEtEr0A0Eo2IVcuWBfB9g) is:

https://gdata.youtube.com/feeds/users/UCqAEtEr0A0Eo2IVcuWBfB9g/uploads

There is an API version 3.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Als
  • 1,387
  • 1
  • 10
  • 5
2

From https://stackoverflow.com/a/65440501/2585501:

This method is especially useful if a) the channel has more than 50 videos or if b) desire youtube video ids formatted in a flat txt list:

  1. Obtain a Youtube API v3 key (see https://stackoverflow.com/a/65440324/2585501)
  2. Obtain the Youtube Channel ID of the channel (see https://stackoverflow.com/a/16326307/2585501)
  3. Obtain the Uploads Playlist ID of the channel: https://www.googleapis.com/youtube/v3/channels?id={channel Id}&key={API key}&part=contentDetails (based on https://www.youtube.com/watch?v=RjUlmco7v2M)
  4. Install youtube-dl (e.g. pip3 install --upgrade youtube-dl or sudo apt-get install youtube-dl)
  5. Download the Uploads Playlist using youtube-dl: youtube-dl -j --flat-playlist "https://<yourYoutubePlaylist>" | jq -r '.id' | sed 's_^_https://youtu.be/_' > videoList.txt (see https://superuser.com/questions/1341684/youtube-dl-how-download-only-the-playlist-not-the-files-therein)
user2585501
  • 596
  • 4
  • 17
  • 1
    To Download the List one can use Youtube API, too. There is no need to use additional tools like `youtube-dl` – Tom Jan 31 '22 at 09:59
2

Posting long after the original question was asked, but I made a python package that does this using a very simple API. It gets all the videos uploaded to a channel, but I'm not sure about this part (included in the original question):

Videos uploaded to a channel can be from multiple users thus I don't think providing a user parameter would help...

Maybe YouTube changed in the 8 years since this question was posted, but if it didn't, the package I made might not cover this case.

To use the API:

pip3 install -U yt-videos-list # macOS
pip  install -U yt-videos-list # Windows

# if that doesn't work, try
python3 -m pip install -U yt-videos-list # macOS
python  -m pip install -U yt-videos-list # Windows

Then open up a python interpreter

python3   # macOS
python    # Windows

and run the program:

from yt_videos_list import ListCreator
lc = ListCreator()

help(lc) # display API information - shows available parameters and functions

my_url = 'https://www.youtube.com/user/1veritasium'

lc.create_list_for(url=my_url)
slow-but-steady
  • 961
  • 9
  • 15
1

Sample solution in Python. Help taken from this video: video Like many other answers, upload id is to be retrieved from the channel id first.

import urllib.request
import json

key = "YOUR_YOUTUBE_API_v3_BROWSER_KEY"

#List of channels : mention if you are pasting channel id or username - "id" or "forUsername"
ytids = [["bbcnews","forUsername"],["UCjq4pjKj9X4W9i7UnYShpVg","id"]]

newstitles = []
for ytid,ytparam in ytids:
    urld = "https://www.googleapis.com/youtube/v3/channels?part=contentDetails&"+ytparam+"="+ytid+"&key="+key
    with urllib.request.urlopen(urld) as url:
        datad = json.loads(url.read())
    uploadsdet = datad['items']
    #get upload id from channel id
    uploadid = uploadsdet[0]['contentDetails']['relatedPlaylists']['uploads']

    #retrieve list
    urld = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId="+uploadid+"&key="+key
    with urllib.request.urlopen(urld) as url:
        datad = json.loads(url.read())

    for data in datad['items']:
        ntitle =  data['snippet']['title']
        nlink = data['contentDetails']['videoId']
        newstitles.append([nlink,ntitle])

for link,title in newstitles:
    print(link, title)
Ananth
  • 1,798
  • 2
  • 11
  • 8
1

Using the gapi JavaScript API, you can do this

<script src="https://apis.google.com/js/api.js"></script>
const start = () => {
  gapi.client
    .init({
      apiKey: "your_youtubeApiKey",
      discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"],
      scope: "https://www.googleapis.com/auth/youtube.readonly",
    })
    .then(() => {
      console.log("gapi.client initiated");
    })
    .then(() =>
      gapi.client.youtube.channels.list({
        part: "snippet,contentDetails,statistics",
        id: "youtube_channelId",
        // forUsername: 'Bankless',
      })
    )
    .then(
      (res) =>
        // get the youtube related playlist id
        res.result.items[0].contentDetails.relatedPlaylists.uploads
    )
    .then((playlistId) =>
      gapi.client.youtube.playlistItems.list({
        part: "snippet",
        playlistId,
        maxResults: 50,
      })
    )
    .then((res) =>
      // get youtube videos snippets
      res.result.items.map((item) => item.snippet)
    )
    .then((snippets) =>
      snippets.map((snippet) => {
        const { title, description, resourceId } = snippet;
        const { videoId } = resourceId;
        return { title, description, videoId };
      })
    )
    .then((videos) => {
      console.log(videos);
    })
    .catch((err) => console.error(err));
};
gapi.load("client", start);

Docs:

Gianfranco P.
  • 10,049
  • 6
  • 51
  • 68
0

That's my Python solution, using Google API. Observations:

  • Create a .env file to store your API Developer Key, and put it in your .gitignore file
  • The parameter "forUserName" should be set with the name of the Youtube Channel (username). Alternatively, you can use the channel id, setting the parameter "id", instead of "forUserName".
  • The object "playlistItem" gives you access to each video. I'm showing only its title but there are many other properties.
import os
import googleapiclient.discovery
from decouple import config
def main():
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    DEVELOPER_KEY = config('API_KEY')

    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, developerKey = DEVELOPER_KEY)

    request = youtube.channels().list(
        part="contentDetails",
        forUsername="username",
        # id="oiwuereru8987",
    )

    response = request.execute()
    for item in response['items']:
        playlistId = item['contentDetails']['relatedPlaylists']['uploads']
        nextPageToken = ''
        while (nextPageToken != None):
            playlistResponse = youtube.playlistItems().list(
                part='snippet',
                playlistId=playlistId,
                maxResults=25,
                pageToken=nextPageToken
            )
            playlistResponse = playlistResponse.execute()
            print(playlistResponse.keys())
            for idx, playlistItem in enumerate(playlistResponse['items']):
                print(idx, playlistItem['snippet']['title'])
            if 'nextPageToken' in playlistResponse.keys():
                nextPageToken = playlistResponse['nextPageToken']
            else:
                nextPageToken = None

if __name__ == "__main__":
    main()

Example for the .env file

API_KEY=<Key_Here>
0

I want to note here that all answers require the Uploads channel. However to find that, you'll need the Youtube accounts CHANNEL ID. This is not by default available to users on the front end. To find this, simply view the source of the page for the Youtube account and look for the RSS xml link! The ChannelID appears to be another version of the Username but you can then query the API using the id=[ID] field as opposed to forUsername

For example look for the following in the page source: `href="https://www.youtube.com/feeds/videos.xml?channel_id=[ID]"

This can be achieved (in PHP) with the following:

$page = file_get_contents($url);

preg_match('#href="https://www.youtube.com/feeds/videos.xml\?channel_id=([^"]*)"#',$page,$matches);

You can then call the following through the API: https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id=[$matches[1]]&key=[API KEY] to getthe Uploads channel as the other answers have given.

Antony
  • 3,875
  • 30
  • 32
-5

You have to get the channel_id of the video you want to get the data from.

For getting the channel_id using the video_id, you can use the videos:list endpoint of the YouTube Data API - add video_id in Id parameter. example.

Then, with the channel_id, change the second character to "U" :

This modified id is the Uploads playlist of that said YouTube channel.

With this Uploads playlist_id, you can use the Playlistitem:list endpoint of the YouTube Data API to retrieve all the uploaded videos from the channel.

In the part parameter add "id,snippet,contentDetails,status". and in playlistID add the modified channel ID. and then execute.

Armaan
  • 15
  • 8
Singh
  • 2,151
  • 3
  • 15
  • 30