Pulling Google Analytics data into your .Net Application

It would be nice to show the reports you have in Google Analytics on your own site especially if your site has a backoffice or an admin area where you can show a few reports on things about your site. There is a .NET  API that Google started to make it easier to call their own APIs (e.g. YouTube API, Analytics API). However, there is not much example right now and without telling you how the API works, you have to dig in in both the source code of the .NET API and the documentation of the Google API to understand how things work, and make it work for you.

To give credits to the Google API Team, they have created an example on how to use the TaskService and that sample project can be viewed here. We will use that as a template to show how you can query your GA data or reports using the .NET API.

The first thing we need to do is to make sure that you have the latest version of the .NET API. Once you have it, reference the Google.Apis.Analytics.v3.dll file. Now we go to changing some code. Remember that we are not building an example from scratch but instead creating a solution that is based on this template. Make sure you have at least browsed through that code so you can have a better understanding of what we will do here.

Declare an instance of the AnalyticsService

private static AnalyticsService _analyticsService;

Change the scope to Scopes.Analytics

There is a variable scope declared inside the method GetAuthorization. Change that declaration into this:

string scope = AnalyticsService.Scopes.Analytics.GetStringValue();

Initialize the GA Service

The last thing you need to do is to initialize your GA sevice and you that by doing

if (_analyticsService == null)
    _analyticsService = new AnalyticsService(
        new BaseClientService.Initializer()
            Authenticator = _authenticator = CreateAuthenticator();

Now you are ready to do pull your reports or data from GA into your .net application. Here’s a sample request that you can make with the changes we have done.

// make a request
var request = _analyticsService.Data.Ga.Get(
// run the request and get the data
var data = request.Fetch();

The  GetRequest has four required parameters and those are:

  • ids – Unique table ID for retrieving report data. This is the Analytics profile id
  • startDate – Start date for fetching report data
  • endDate – End date for fetching report data
  • metrics – A comma-separated list of Analytics metrics

To know more about the acceptable format and valid values for those parameter, you can visit the Query Explorer.