Raj Rajput
Raj Rajput

Reputation: 115

YouTube Analytics API

I am newbie for Google apis and wanted to start on working YouTube Analytics API to generate reports.I have created project in side Google developer console.When I click on credentials there are two options - OAuth and Public API access .I am not able to understand with which way I should go OAuth or Public API access .For OAuth while creating new client id there are three options - Web application,Service Account and Installed application so here also which is recommended way ?Please help me to understand this things.

Note : Our requirement is to use YouTube Analytics API to generate reports for uploaded videos on our clients channel.

Upvotes: 1

Views: 2437

Answers (3)

Shubhankar
Shubhankar

Reputation: 72

Use Oauth2.0 authentication ,and select web application,this will need to authenticate yourself for the particular channel(as either you are channel owner or contributer) from which you want to retrieve the data.

After authenticating, you can save the token in a file, and it will automatically refresh the token, when the token is expired,use this thread to save the file.

From Documentation : Access tokens periodically expire and become invalid credentials for a related API request. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.

Do not use service account for Youtube Analytics Api as it is not supported:

The YouTube Analytics API does not support the service account flow. From Documentation

Upvotes: 0

RZ Wuronz
RZ Wuronz

Reputation: 11

After creating a project from developer console you can try to following this tutorial (in french), at the bottom there is the complete fuction for reporting everything from the Youtube API analytics.

here is the function to get data from both Youtube API and Youtube analytics API

don't forget to add your client_secrets.json to your \bin\Debug\netcoreapp3.1

    public async void FetchYoutubeAnalyticsAPI()
    {
        UserCredential credential;
        using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            new[] { YouTubeService.Scope.YoutubeReadonly },
            "user",
            CancellationToken.None
            );
        }

        var youTubeAnalyticsService = new YouTubeAnalyticsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
        });

        var request = youTubeAnalyticsService.Reports.Query();
        request.StartDate = ("2019-01-01");
        request.EndDate = ("2020-09-30");
        request.Ids = ("channel==UCmLQ3sdAd6CypJIne5ZANaA");
        request.Metrics = ("views,comments,likes,dislikes,estimatedMinutesWatched,averageViewDuration");
      
        QueryResponse requestquery = request.Execute();

        List<int> myChannelDataList = new List<int>();

        int listsize = 0;
        foreach (object obj in requestquery.Rows[0])
        { 
            int value = Convert.ToInt32(obj);
            myChannelDataList.Add(value);
      /*      Debug.WriteLine("Value : " + value);
            Debug.WriteLine("LISTE / " + myChannelDataList[0]);
            Debug.WriteLine("Count : " + myChannelDataList.Count);*/
            listsize = myChannelDataList.Count;
        }
        List<string> metrics = new List<string> { "Vues", "Commentaires", "Likes", "Dislike", "Minutes", "MoyenneTemps" };
        for (int i = 0; i < listsize; i++)
        {
            Label labels = new Label();
            labels.Top = (i + 4) * 20;
            labels.Left = 100;
            labels.AutoSize = true;
            labels.TextAlign = ContentAlignment.MiddleLeft;
            labels.Text = metrics[i] + " :" + myChannelDataList[i].ToString();
            this.Controls.Add(labels);
        }


        // https://developers.google.com/youtube/v3/docs/channels/list
        var youtubeService = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
        });
        var requestSub = youtubeService.Channels.List("statistics");
        requestSub.Mine = (true);

        ChannelListResponse responsesub = requestSub.Execute();

        foreach (var sresults in responsesub.Items)
        {
            var substats = sresults.Statistics;
            var subcount = substats.SubscriberCount;
            var viewCount = substats.ViewCount;
            var videoCount = substats.VideoCount;
            var commentsCount = substats.CommentCount;

            Debug.WriteLine("SubCount : " + subcount);

            Label labels = new Label();
            labels.Top = 16;
            labels.Left = 280;
            labels.AutoSize = true;
            labels.TextAlign = ContentAlignment.MiddleLeft;
            labels.Text = "Subs :" + subcount;
            this.Controls.Add(labels);
        }
    }

enter image description here

Upvotes: 0

Nick Knuckle
Nick Knuckle

Reputation: 106

When it comes to private user data, OAuth 2.0 is the recommended authorization method for the Analytics API. If you're collecting and storing data to be used on your end, you most likely want to go with the server-side application approach.

From the documentation:

  • The server-side flow supports web applications that can securely store persistent information.
  • The client-side flow supports JavaScript applications running in a browser.
  • The installed application flow supports applications installed on a device, such as a phone or computer.

From the documentation on the service account option:

The service account flow supports server-to-server interactions that do not access user information. However, the YouTube Analytics API does not support this flow. Since there is no way to link a Service Account to a YouTube account, attempts to authorize requests with this flow will generate an error.

There's a lot of documentation on all of these options provided to you, I'd recommend reading through it in its entirety to make sure you have a firm grasp on the concepts. Click here to read about OAuth 2.0 with the YouTube Analytics API

Cheers!

Edit: Just to be completely clear, if you're collecting data through a backend application, use the "Service Account" option for generating OAuth Client IDs. If, however, you're having a interact with the API reports through a web/installed application, you would select "Web/Installed Application". I hope this was helpful and clear.

Upvotes: 2

Related Questions