5

I want to list a bunch of videos from YouTube in my mobile app using angularjs. Preferrably I'd like to list all videos of a user/channels specific playlist.

I've gotten the API KEY from Google Developer Console but I don't understand how and where to use it. In this documentation they only go over the oauth method. https://developers.google.com/youtube/v3/code_samples/javascript#authorizing_requests I tried using the example code straight up from that documentation only to get a message saying I have to authenticate first.

I'd really appreciate some help into this. How do authenticate using the api key and secondly how to make the request to get the videos in a playlist.

ps. I'm a newbie developer and I'm using angularjs and ionic framework for my first learning project. I'm fresh out of Codeschool's courses in css, jquery, javascript, backbone and angular. ds. Thanks!

Tommy Sollén
  • 251
  • 2
  • 4
  • 12

2 Answers2

15

1. How to use the API

If you want videos of a channel you need to use the YouTube API V3. Use youtube.search.list

with the parameters :

part=id, snippet
channelId=ID OF THE CHANNEL
order=date
type=video

How to find ID of a YouTube Channel ?

You can find the id of a channel with his channel name with http://mpgn.github.io/YTC-ID/

More information of youtube.search.list right here.

This is a live demo.

2. With Javascript ?

  • First, you need to creat a project in console.google.developers.
  • Enable the API YouTube API V3 (set to on).
  • In credential part, creat a public access key.

Also if it's a public app, you may interest by : How to protect my public API key ?

This is the basic code to get the videos of a channel :

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <script>

function googleApiClientReady() {

    var apiKey = 'your api key';

    gapi.client.setApiKey(apiKey);
    gapi.client.load('youtube', 'v3', function() {

        request = gapi.client.youtube.search.list({
            part: 'snippet',
            channelId: 'UCqhNRDQE_fqBDBwsvmT8cTg',
            order: 'date',
            type: 'video'

        });

        request.execute(function(response) {
                console.log(response);

        });
    });

}
  </script>
    <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>

3. With AngularJS ?

With AngularJS you need to creat a service 'google' for example, and you can use the service in your controllers.

An sample example : https://gist.github.com/jakemmarsh/5809963 You don't need the part with authentification. Using deferred is important in this case.

Example in the controller

'use strict';

function init() {
    window.initGapi(); // Calls the init function defined on the window
}
angular.module('team')
    .controller('VideosCtrl', function ($scope, $window, $sce, googleService) {

        $window.initGapi = function() {
            $scope.$apply($scope.getChannel);
        };

        $scope.getChannel = function () {
            googleService.googleApiClientReady().then(function (data) {
                $scope.channel = data;
            }, function (error) {
                console.log('Failed: ' + error)
            });
        };
    });

Example in the service googleService

.service('googleService', ['$http', '$q', function ($http, $q) {

    var deferred = $q.defer();
    this.googleApiClientReady = function () {
        gapi.client.setApiKey('YOU API KEY');
        gapi.client.load('youtube', 'v3', function() {
            var request = gapi.client.youtube.playlistItems.list({
                part: 'snippet',
                playlistId: 'PLila01eYiSBjOtR8oqXkY0i5c1QS6k2Mu',
                maxResults: 8
            });
            request.execute(function(response) {
                deferred.resolve(response.result);
            });
        });
        return deferred.promise;
    };
}])

You need to add this line to your index.html

<script src="https://apis.google.com/js/client.js?onload=init"></script>

Hope it's help you !

Community
  • 1
  • 1
mpgn
  • 7,121
  • 9
  • 67
  • 100
  • Thanks @martialdidi! But now I'm stuck... I made it fine to part 3. I created a service but then I don't know how to use the controller to get the data ondo the DOM. Can you help out? – Tommy Sollén Sep 11 '14 at 21:04
  • 3
    you mean you don't know how to use AngularJS ? – mpgn Sep 11 '14 at 21:16
  • Haha yes. I'm a newbie developer and I'm using angularjs and ionic framework for my first learning project. I'm fresh out of Codeschool's courses in css, jquery, javascript, backbone and angular. Sorry, I forgot to mention my n00b status in this question. I usually do. – Tommy Sollén Sep 11 '14 at 21:36
  • Just out of curiosity, isn't the api key would expose to public if the program is done this way? Any idea to make these confidential information stay confidential? – Justin Moh May 09 '15 at 14:30
  • @JustinMoh part 2: "Also if it's a public app, you may interest by : How to protect my public API key ?" – mpgn May 09 '15 at 14:53
  • @mpgn can you please help me to upload video i am not able to upload it. i am posting my question soon as ill git your replay – Nasiruddin Saiyed Feb 06 '18 at 06:32
1

You have to use Google APIs Client Library so that gapi object will be defined and examples from google will work. Include this in the bottom of the page:

<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>

And than define callback which will proceed with authorization and your logic:

googleApiClientReady = function() {
  gapi.auth.init(function() {
    // Other code following the example
  });
}

In general as per Google documentation there are

  1. The application loads the JavaScript client library.

  2. The application references its API key, which authenticates the application with Google services.

  3. If the application needs access to the user's personal information, it opens a session with a Google auth server. The auth server opens a dialog box which prompts the user to authorize the use of personal information.

  4. The application loads the API for the Google service.

  5. The application initializes a request object (also called a service object) that specifies the data to be returned by the API.

  6. The application executes the request and processes the data returned by the API.

Here is a working example of basic google API authorization process

Community
  • 1
  • 1
2ooom
  • 1,760
  • 1
  • 23
  • 37