70

With Youtube api v2, there's easy way to get videos. Just send a query like this:

http://gdata.youtube.com/feeds/mobile/videos?max-results=5&alt=rss&orderby=published&author=OneDirectionVEVO

The Youtube api v2 also has an interactive demo page for building query: http://gdata.youtube.com/demo/index.html

With Youtube api v3, I don't know the corresponding way. Please point me the way with api v3.

Thank you!

Limon Monte
  • 52,539
  • 45
  • 182
  • 213
vietstone
  • 8,784
  • 16
  • 52
  • 79
  • Possible duplicate of [How do I get a list of uploaded videos for a certain channel with the new YouTube Data API (V3)?](http://stackoverflow.com/questions/13504899/how-do-i-get-a-list-of-uploaded-videos-for-a-certain-channel-with-the-new-youtub) – Cédric M. Dec 29 '15 at 18:43
  • I noticed that the video from Youtube's API reference is very outdated, and since lots of people were struggling to make it work, I created this 5m **video tutorial** to help users to **generate an API key** and also to **enable the youtube API** so that any endpoint will work properly: https://www.youtube.com/watch?v=MdQDYtytEbY – sergioviniciuss Jul 30 '17 at 00:08
  • https://stackoverflow.com/questions/18953499/youtube-api-to-fetch-all-videos-on-a-channel – Naresh Jul 01 '19 at 06:33

13 Answers13

134

The channels#list method will return a JSON with some information about the channel, including the playlist ID for the "uploads" playlist:

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

With the playlist ID you can get the videos with the playlistItems#list method:

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUbW18JZRgko_mOGm5er8Yzg&key={YOUR_API_KEY}

You can test those at the end of the documentation pages.

Vinicius Braz Pinto
  • 8,209
  • 3
  • 42
  • 60
  • Hi, your answer is perfect. But I have one more question. Because not all video can be played in mobile, api v2 have an option to pass "mobile" parameter in the query. How do I pass "mobile" parameter in api v3? Thank you – vietstone Mar 25 '14 at 02:15
  • The docs for v3 doesn't mention that. I see that the videos#list method can return a `embeddable` property if you ask for the "status" part, but I'm not sure if it means it can be played on mobile. And you'd have to call it for each video https://developers.google.com/youtube/v3/docs/videos/list – Vinicius Braz Pinto Mar 25 '14 at 03:30
  • 8
    I found it. From https://developers.google.com/youtube/v3/docs/search/list , I can use the query https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCbW18JZRgko_mOGm5er8Yzg&order=date&type=video&videoSyndicated=true&key={YOUR_API_KEY} – vietstone Mar 25 '14 at 16:36
  • 5
    I was confuse with what is YOUR_API_KEY - after play around I got - https://console.developers.google.com -> your API project -> APIs & auth -> Credentials -> Public API Access -> Server Key – Ramratan Gupta May 26 '15 at 10:02
  • 1
    Any ideas why the returned JSON is sorted differently. The videos are the same but the sort order is different than on the actual videos page. I can't find a sort parameter by uploaded date/published date. Thank you – orbitory Jun 15 '15 at 14:04
  • 3
    @orbitory apparently sorting is a missing feature, see this issue https://code.google.com/p/gdata-issues/issues/detail?id=6869 and a possible "solution" here: http://stackoverflow.com/questions/22893328/sorting-youtube-api-result-from-playlist – Vinicius Braz Pinto Jun 15 '15 at 23:13
  • I ended up using youtube/v3/activities?part=snippet%2CcontentDetails&channelId='.$channelId.'&maxResults=50&key='.$key and filtering by $post['snippet']['type'] == 'upload'. Turns out activities also shows added playlist items so you might get duplicates – orbitory Jun 17 '15 at 00:17
  • 4
    Wow! two json call to see my own videos? – Gino Jul 02 '15 at 17:17
  • hey how to get like count dislike count and view count of each video using playlist ID?? – kundan roy Jan 06 '16 at 16:38
  • 1
    What if the user doesn't have an username, just channel id? – Turqueso Apr 14 '16 at 17:38
  • 1
    @Turqueso I think instead of `forUsername` you'd pass the `id` parameter with the channel id – Vinicius Braz Pinto Apr 16 '16 at 14:01
  • https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=OneDirectionVEVO&key={YOUR_API_KEY} – Ganpat Kaliya Jun 14 '16 at 10:19
  • this url is working fine when I get channel list using "oneDirectionVevo" user name but when I try my userName like "Ganpat%20Kaliya" this url gives me emty Items array. why this happened can you tell me where is my error ? also in my playlist contains one video but it returns emplty list – Ganpat Kaliya Jun 14 '16 at 10:22
  • this is my email please reply on this ganpat.kaliya@gmail.com – Ganpat Kaliya Jun 14 '16 at 10:22
  • 1
    @GanpatKaliya you should use the channel ID, not your username. Go to your channel on YouTube and see the ID in the URL, after `/channel/` – Vinicius Braz Pinto Jun 15 '16 at 12:39
  • I need to use the YouTube data api to pull videos from a channel and literally embed the videos into a web page so users can click on them. – DtechNet Feb 16 '17 at 05:21
  • Also this is only any good if the number of videos to list is <50 and pagination is not mentioned. – volvox Feb 12 '18 at 20:28
25

This should do it. This code just gets and outputs the title but you can get any details you want

// Get Uploads Playlist
$.get(
   "https://www.googleapis.com/youtube/v3/channels",{
   part : 'contentDetails', 
   forUsername : 'USER_CHANNEL_NAME',
   key: 'YOUR_API_KEY'},
   function(data) {
      $.each( data.items, function( i, item ) {
          pid = item.contentDetails.relatedPlaylists.uploads;
          getVids(pid);
      });
  }
);

//Get Videos
function getVids(pid){
    $.get(
        "https://www.googleapis.com/youtube/v3/playlistItems",{
        part : 'snippet', 
        maxResults : 20,
        playlistId : pid,
        key: 'YOUR_API_KEY'},
        function(data) {
            var results;
            $.each( data.items, function( i, item ) {
                results = '<li>'+ item.snippet.title +'</li>';
                $('#results').append(results);
            });
        }
    );
}


<!--In your HTML -->
<ul id="results"></ul>
Brad
  • 309
  • 3
  • 8
5

If quota cost is a consideration, it may be beneficial to follow this simple algorithm.

First grab the data from https://www.youtube.com/feeds/videos.xml?channel_id=... This is a simple XML feed which will give you the video ID's, but you cannot specify further 'parts' (stats, etc).

Using the video ID's from that list, do a query on the /videos API endpoint which allows for a comma-separated-list of video ID's which should only result in 1 quota cost, plus 0-2 for any additional part parameters. As @chrismacp points out, using the /search endpoint is simpler but has a quota cost of 100, which can add up quickly.

There is a resource consideration here (cpu, memory, etc) as you are making a second call, but I believe in many scenarios this can be a useful method.

Appl3s
  • 177
  • 3
  • 11
  • 1
    The XML feed only contains the 15 most recent uploads from the channel, though, which is insufficient for many purposes. – Tuesday Feb 13 '17 at 20:56
  • @timothymh this is true, thank you for making this important point. Regardless, if 15 is sufficient for your needs, as it was for mine, then hopefully others may find this alternative to be useful. – Appl3s May 17 '17 at 16:42
  • Absolutely true. I've actually had occasion to use this method myself! :) – Tuesday May 17 '17 at 16:43
4

Things have changed alot in V3 of the API. Here is a video that walks you through the v3 API calls needed to get a list of the videos uploaded in a given channel, with live demos using the API Explorer.

YouTube Developers Live: Getting a Channel's Uploads in v3 - https://www.youtube.com/watch?v=RjUlmco7v2M

Babatunde Adeyemi
  • 14,360
  • 4
  • 34
  • 26
3

In case it helps anyone here this is what I discovered and so far seems to be working well for me. I am authenticating the member via OAuth 2.0 prior to making this request, which will give me the authenticated members videos. As always, your personal mileage may vary :D

curl https://www.googleapis.com/youtube/v3/search -G \
-d part=snippet \
-d forMine=true \
-d type=video \
-d order=date \
-d access_token={AUTHENTICATED_ACCESS_TOKEN}
Jonmark Weber
  • 151
  • 2
  • 3
  • This is also how I've been doing it, but I've realized it includes results for videos that have been removed, which is highly annoying. – robbpriestley Sep 08 '16 at 19:19
2

The equivalent of the request you posted is actually a search in the 3.0 api, not a playlist request. It's easier too to do it that way. You do need to excange the username for a channel ID though.

ex. GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUGhCVGZ0ZSpe5hJHWyiLwHA&key={YOUR_API_KEY}

xangadix
  • 21
  • 1
  • 3
    search.list has a quota cost of 100. The channel.list + playlistItems.list combination which would be a quota of 4. Something to bear in mind. – chrismacp Nov 22 '16 at 23:28
1

Here is some code using the offical Google APIs Node library (https://github.com/google/google-api-nodejs-client)

const readJson = require("r-json");
const google = require('googleapis');
const Youtube = google.youtube('v3');

// DONT store your credentials in version control
const CREDENTIALS = readJson("/some/directory/credentials.json");

let user = "<youruser>";
let numberItems = 10; 

let channelConfig = {
  key: CREDENTIALS.youtube.API_KEY,
  part: "contentDetails",
  forUsername: user
};

Youtube.channels.list(channelConfig, function (error, data) {

  if (error) {
    console.log("Error fetching YouTube user video list", error);
    return;
  }

  // Get the uploads playlist Id
  let uploadsPlaylistId = data.items[0].contentDetails.relatedPlaylists.uploads;

  let playlistConfig = {
    part : 'snippet',
    maxResults : size,
    playlistId : uploadsPlaylistId,
    key: CREDENTIALS.youtube.API_KEY
  };

  // Fetch items from upload playlist
  Youtube.playlistItems.list(playlistConfig, function (error, data) {

    if (error) {
      console.log("Error fetching YouTube user video list", error);
    }

    doSomethingWithYourData(data.items);
  });
});
chrismacp
  • 3,834
  • 1
  • 30
  • 37
0

An alternative method may be to get the playlists for the currently oauth authenticated user via: property mine=true

where the oauth access_token is retrieved following authentification: https://developers.google.com/youtube/v3/guides/authentication

https://www.googleapis.com/youtube/v3/playlists?part=id&mine=true&access_token=ya29.0gC7xyzxyzxyz
0

Please don't use playlistitems.list if you want to get the videos of playlist with more then 300 videos. You can try it live in google link "https://developers.google.com/youtube/v3/docs/playlistItems/list" in "Try it" section. It returns undefined.

I have used in my project also. It returns undefined only.

0

In PHP: I used pageToken attribute to go to all page of playlist.I hope it can help you.

//step 1: get playlist id

 $response = file_get_contents("https://www.googleapis.com/youtube/v3/channels?key={$api_key}&forUsername={$channelName}&part=contentDetails");
 $searchResponse = json_decode($response,true);
 $data = $searchResponse['items'];
 $pid =  $data[0]['contentDetails']['relatedPlaylists']['uploads'];

//step 2: get all videos in playlist

 $nextPageToken = '';
 while(!is_null($nextPageToken)) {
     $request = "https://www.googleapis.com/youtube/v3/playlistItems?key={$api_key}&playlistId={$pid}&part=snippet&maxResults=50&pageToken=$nextPageToken";

    $response = file_get_contents($request);
    $videos = json_decode($response,true);

    //get info each video here...

   //go next page
    $nextPageToken = $videos['nextPageToken'];
}
0

In node.js, it can be achieved with following code.

Requires authKey and channelId as options object parameter.

cb callback is called after data is fetched.

async function fetchChannelInfo(options) {
  const channelUrl = `https://www.googleapis.com/youtube/v3/channels?part=contentDetails,statistics&id=${
    options.channelId
  }&key=${options.authKey}`;
  const channelData = await axios.get(channelUrl);

  return channelData.data.items[0];
}
function fetch(options, cb) {
  fetchChannelInfo(options).then((channelData) => {
    options.playlistId = channelData.contentDetails.relatedPlaylists.uploads;
    const paylistUrl = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${
      options.playlistId
    }&key=${options.authKey}`;

    axios
      .get(paylistUrl)
      .then((response) => {
        const payloadData = ;

        const videoList = [];
        response.data.items.forEach((video) => {
          videoList.push({
            publishedAt: video.snippet.publishedAt,
            title: video.snippet.title,
            thumbnails: thumbnails,
            videoId: video.snippet.resourceId.videoId,
          });
        });

        cb(null, videoList);
      })
      .catch((err) => {
        cb(err, null);
      });
  });
}

Note: axios is used for RESTful requests. To install

npm install axios
Nafiz Bayındır
  • 495
  • 7
  • 15
0
$.get(
    "https://www.googleapis.com/youtube/v3/channels",{
      part: 'snippet,contentDetails,statistics,brandingSettings',
      id: viewid,
      key: api},
      function(data){

        $.each(data.items, function(i, item){


          channelId = item.id;
          pvideo = item.contentDetails.relatedPlaylists.uploads;
          uploads(pvideo);
});

      });

Uploads Function can be

function uploads(pvideo){


       $.get(
        "https://www.googleapis.com/youtube/v3/playlistItems",{
          part: 'snippet',
          maxResults:12,
          playlistId:pvideo,
          key: api},
          function(data){


            $.each(data.items, function(i, item){

                 videoTitle = item.snippet.title;
             videoId = item.id;
            description = item.snippet.description;
            thumb = item.snippet.thumbnails.high.url;
            channelTitle = item.snippet.channelTitle;
            videoDate = item.snippet.publishedAt;
            Catagoryid = item.snippet.categoryId;
            cID = item.snippet.channelId;

            })
          }
        );
     }
Shahzaib Chadhar
  • 178
  • 1
  • 10
0

function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}



$(function() {


    $(".form-control").click(function(e) {


       e.preventDefault();


       // prepare the request


       var request = gapi.client.youtube.search.list({


            part: "snippet",


            type: "video",


            q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),


            maxResults: 20,


            order: "viewCount",


            publishedAfter: "2017-01-01T00:00:00Z"


       }); 


       // execute the request


       request.execute(function(response) {


          var results = response.result;


          $("#results").html("");


          $.each(results.items, function(index, item) {


            $.get("tpl/item.html", function(data) {


                $("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId ,"descrip":item.snippet.description ,"date":item.snippet.publishedAt ,"channel":item.snippet.channelTitle ,"kind":item.id.kind ,"lan":item.id.etag}]));


            });


            


          });


          resetVideoHeight();


       });


    });


    


    $(window).on("resize", resetVideoHeight);


});



function resetVideoHeight() {


    $(".video").css("height", $("#results").width() * 9/16);


}



function init() {


    gapi.client.setApiKey("YOUR API KEY .... USE YOUR KEY");


    gapi.client.load("youtube", "v3", function() {


        // yt api is ready


    });


}

Check the Complete code here https://thecodingshow.blogspot.com/2018/12/youtube-search-api-website.html

R P S Naik
  • 11
  • 1