Analytics Reporting API V4 Client Library for .NET

29,179

Solution 1

Calling the Google Analytics Reporting API from C# is not particularly difficult, however all of the necessary steps do not seem to be outlined very clearly in the Google Analytics API documentation. I will try to list them all out here. While YMMV, I believe these steps to be correct as of 7/20/2016.

You can start by creating a new C# project. We'll make a console application to test called GoogleAnalyticsApiConsole. Once the project is created, we'll add a reference to the Google Analytics Reporting API V4 Client Library for .NET using the NuGet Package Manager Console (found under the Tools menu in Visual Studio 2015). Fire up the Console and issue the following command at the PM> prompt:

PM> Install-Package Google.Apis.AnalyticsReporting.v4

Installing that package will download the client libraries needed to call the Google Analytics Reporting web services along with a number of other dependencies.

In order to call the web services, you'll need to set up OAuth 2.0 access for your application. The documentation for this setup can be found here, but I will summarize below:

  1. Login to the Google Cloud Platform Console: https://console.cloud.google.com/. Be sure to login with an account that has access to the Google Analytics accounts you are trying to query with the reporting API.

  2. Click the Google Cloud Platform menu and select API Manager.

Google Cloud Platform API Manager

  1. On the left hand side, click Credentials and then create a new project called Google Analytics API Console. Give it some time to create the new project.

  2. After the project is created, click Credentials again if it is not already selected, and then click the OAuth Consent Screen link in the right panel. Set the Product name shown to users to Google Analytics API Console and then click Save.

  3. Click Credentials again, and then click Create Credentials, and choose OAuth Client ID. Select Other for Application type and then enter Google Analytics API Console as the Name and click Create.

  4. After the credential is created, you will be presented with a client ID and a client secret. You can close the dialog window.

  5. Now, under Credentials you should see an entry under OAuth 2.0 client ids. Click the download icon to the far right of that entry to download the client_secret.json file (this file will have a much longer name). Add that file to your project at the root level once it has been downloaded and rename it to client_secret.json.

Google Cloud Platform API Credentials

  1. Now that the OAuth 2.0 credential has been created, we need to enable it to call the Reporting API. Select Overview and make sure Google APIs is selected in the right panel. Type in Reporting in the search box and select Analytics Reporting API V4 from the list. On the next screen, click Enable. Once this API has been enabled, you should be able to see it under the Enabled APIs list in the right panel.

Google Cloud Platform Enabled Analytics Reporting

Now that we've created our project and created our OAuth 2.0 credential, it is time to call the Reporting API V4. The code listed below will use the Google API and the client_secret.json file to create a Google.Apis.Auth.OAuth2.UserCredential to query the Reporting API for all sessions between the given date range for a View. The code is adapted from the Java example here.

Before executing the code, be sure to set the Build Action on the client_secret.json file to Content and the Copy to Output Directory setting to Copy if newer. There are also two variables that need to be properly set. First, in the GetCredential() method, set the loginEmailAddress value to the email address used to create the OAuth 2.0 credential. Then, in the Main method, be sure to set the ViewId in the reportRequest variable to the view that you want to query using the Reporting API. To find the ViewId, log in to Google Analytics and select the Admin tab. From there, select the view you want to query in the View dropdown on the far right and select View Settings. The View ID will be displayed under Basic Settings.

The first time the code is executed, it will bring up a web page asking if you want to allow the Google Analytics API Console to have access to the API data. Select Allow to proceed. From then on that permission will be stored in the GoogleAnalyticsApiConsole FileDataStore. If that file is deleted, then permission will need to be granted again. That file can be found in the %APPDATA%\GoogleAnalyicsApiConsole directory.

Google API Permission OAuth 2.0

Please note that I believe this scenario will meet the needs of the OP. If this application were to be distributed to clients, then a different OAuth 2.0 scheme would most likely be necessary.

Here is the code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.AnalyticsReporting.v4.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;

namespace GoogleAnalyticsApiConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var credential = GetCredential().Result;
                using(var svc = new AnalyticsReportingService(
                    new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Google Analytics API Console"
                    }))
                {    
                    var dateRange = new DateRange
                    {
                        StartDate = "2016-05-01",
                        EndDate = "2016-05-31"
                    };
                    var sessions = new Metric
                    {
                        Expression = "ga:sessions",
                        Alias = "Sessions"
                    };
                    var date = new Dimension { Name = "ga:date" };

                    var reportRequest = new ReportRequest
                    {
                        DateRanges = new List<DateRange> { dateRange },
                        Dimensions = new List<Dimension> { date },
                        Metrics = new List<Metric> { sessions },
                        ViewId = "<<your view id>>"
                    };
                    var getReportsRequest = new GetReportsRequest {
                        ReportRequests = new List<ReportRequest> { reportRequest } };
                    var batchRequest = svc.Reports.BatchGet(getReportsRequest);
                    var response = batchRequest.Execute();
                    foreach (var x in response.Reports.First().Data.Rows)
                    {
                        Console.WriteLine(string.Join(", ", x.Dimensions) +
                        "   " + string.Join(", ", x.Metrics.First().Values));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        static async Task<UserCredential> GetCredential()
        {
            using (var stream = new FileStream("client_secret.json", 
                 FileMode.Open, FileAccess.Read))
            {
                const string loginEmailAddress = "<<your account email address>>";
                return await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { AnalyticsReportingService.Scope.Analytics },
                    loginEmailAddress, CancellationToken.None, 
                    new FileDataStore("GoogleAnalyticsApiConsole"));
            }
        }
    }
}

Solution 2

Here are the steps updated for Sep 2019.

First, understand that there are two choices under OAuth: User credentials and Service Account credentials. User credentials are meant to be used when you do not know which Google Analytics account you will be connected to, hence the user grants your application permission. Service Account credentials are meant to be used, e.g. if you build your own dashboard for your company to display Google Analytics data.

Most of the time, if you need programmatic access to Analytics data, it is the second case.

The steps below should get you started for a simple C# example. Note that the Google web console part may vary slightly, but should be easy to find nevertheless.

  1. Go to the Google API Console. Create a Project if prompted.
  2. Go to Service accounts.
  3. Create a new Service Account. You should have an account with a random-generated email address (mine is ending with [email protected])
  4. Find the Create Key button. Choose JSON and download the file. This is your private key and your only copy. Do not lose it.
  5. Go to your Google Analytics admin panel. Grant access to the Service Account using its email address, the same way you would grant access to other users.

The Google configuration is done. Now jump into Visual Studio.

  1. Create a new C# Console Project.
  2. Get the Nuget package Google.Apis.AnalyticsReporting.v4. It should also automatically download the core packages as well.
  3. Grab the JSON file downloaded earlier, put it in the project, set its Property to Content and Copy Always.
using Google.Apis.AnalyticsReporting.v4.Data;
using System;

namespace ConsoleApplication {
    class Program {
        static void Main(string[] args) {
            var credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromFile("serviceAccount.json")
                .CreateScoped(new[] { Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService.Scope.AnalyticsReadonly });

            using (var analytics = new Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService(new Google.Apis.Services.BaseClientService.Initializer {
                HttpClientInitializer = credential
            })) {
                var request = analytics.Reports.BatchGet(new GetReportsRequest {
                    ReportRequests = new[] {
                        new ReportRequest{
                            DateRanges = new[] { new DateRange{ StartDate = "2019-01-01", EndDate = "2019-01-31" }},
                            Dimensions = new[] { new Dimension{ Name = "ga:date" }},
                            Metrics = new[] { new Metric{ Expression = "ga:sessions", Alias = "Sessions"}},
                            ViewId = "99999999"
                        }
                    }
                });
                var response = request.Execute();
                foreach (var row in response.Reports[0].Data.Rows) {
                    Console.Write(string.Join(",", row.Dimensions) + ": ");
                    foreach (var metric in row.Metrics) Console.WriteLine(string.Join(",", metric.Values));
                }
            }

            Console.WriteLine("Done");
            Console.ReadKey(true);
        }
    }
}

Solution 3

I had the same experience: Google's documentation is pretty in-depth but is pretty terrible at giving clear examples of how to connect with .NET.

One key thing I finally realized is that you can either connect using an OAuth2 credential or a service account credential. If you own your Analytics account, use a service account. If you're needing to connect to other users' Analytics accounts, use OAuth2.

There seem to be quite a few examples online of how to get Analytics API data using an OAuth2 credential, but I own my Analytics account and just wanted to pull data from it. I figured out how to connect to the Analytics Reporting API v4 using a ServiceAccountCredential, and I wrote an answer on a similar Stack Overflow question with all the details.

Share:
29,179

Related videos on Youtube

Ben
Author by

Ben

Updated on July 09, 2022

Comments

  • Ben
    Ben almost 2 years

    I'm trying to get some data from our google analytics instance and I'd like to use the Analytics Reporting API V4 Client Library for .NET (https://developers.google.com/api-client-library/dotnet/apis/analyticsreporting/v4) so that I can bake some of this data into an administration site we have built. I'm having trouble finding any examples of using this code and the documentation seems to be incredibly sparse. I would like to use a service account to authorize as we only need to view data associated with the analytics account which we control.

    If anyone could provide some sample code or point me in the right direction to get some basic report data using the .net api, it would be greatly appreciated

    • Matt
      Matt almost 8 years
      The client library docuementation applies for all Google APIs. As for making the particular requests you can see the V4 API Samples in various languages and map it to dot net.
    • Ben
      Ben almost 8 years
      I eventually did figure out how to make a request using the .net client libraries but this is definitely not intuitive. I will post some sample code if I have some extra time
    • Gabriël
      Gabriël almost 8 years
      Would be great if you found that time :)
    • Ian Routledge
      Ian Routledge almost 8 years
      @Ben could you post any sample code please?
  • TrueWill
    TrueWill over 7 years
    Note that AnalyticsReportingService implements IDisposable and should be wrapped in a using block.
  • Daevin
    Daevin over 7 years
    When I use this, a new tab opens of a Google app (with 'Developer info' email the same as the account I'm using the Google Analytics for) requesting access to my personal Gmail account (which I'm logged into Chrome as)... why is this happening?
  • rsbarro
    rsbarro over 7 years
    @Daevin Wish I could be more helpful here but I'm really not sure why you are seeing that. Did you log into the Google Cloud Platform Console with an account that has access to your GA data? Did you request access to any APIs other than Analytics Reporting API V4?
  • rsbarro
    rsbarro over 7 years
    @TrueWill thank you for the comment - you are correct. I updated the code to include a using statement around the AnalyticsReportingService instance.
  • Daevin
    Daevin over 7 years
    @rsbarro No, I signed into the GCP Console in Incognito using the desired account (not my personal one) and used that same email address your code sample for loginEmailAddress to get the credentials. As soon as I ran the project, it opened my site's page in the non-Incognito window and started loading, then it opened a new tab asking permissions for my personal account. In the GCP, I only added the API V4 to the list (per your instructions). I also opened my site's page in Incognito and it still opened a window in the non-Incognito window asking for my personal account's permission.
  • rsbarro
    rsbarro over 7 years
    I would try logging out of your personal account in non-incognito mode and run through it again. If you are still having problems, I would consider posting a separate question, so you can include more information. Feel free to link to it here in the comments and I will take a look (if others don't answer first). I don't think it makes sense to try to work through the issue here in the comments.
  • rollsch
    rollsch over 7 years
    Great answer. Very informative. Do you have a blog?
  • AGB
    AGB almost 7 years
    An incredibly useful and well written answer, especially given the lack of documentation available.
  • Dmitry
    Dmitry over 6 years
    OP needs to access their own GA property. Shouldn't they be creating a 'Service account key' instead of OAuth client ID (that requests user consent)? My understanding is that this avoids the whole interactive part where they have to grand the permission. The private key is generated right away for Service accounts.
  • jonju
    jonju over 4 years
    This is exactly what I was looking for. Thank you man, it really helped
  • user3585193
    user3585193 about 4 years
    Having trouble reading client_secret.json file, using aws-lamda c#, any ideas please ?
  • Brandon
    Brandon almost 4 years
    Agreed. This worked perfectly and finally got me where I needed to be as a starting point for getting GA Data loaded into SQL Server.
  • James Rao
    James Rao almost 3 years
    Hi, anyone knows where to find the default built-in Dimensions and Metrics in V4?
  • geriwald
    geriwald almost 3 years
    This should be the accepted answer. I wasted time trying to setup user credentials ! I guess I can only blame myself for not browsing through the answers first.
  • Chris Harrington
    Chris Harrington over 2 years
    Hoping to convert this example to use an oauth refresh token. Does anyone have such an example?
  • Borislav Nanovski
    Borislav Nanovski almost 2 years
    In 2022 there are no more views in GA. Do you guys happen to know what requests are there to be made via the GA v4 API for .netcore? If not views, what?