Home > Uncategorized > Accessing the Google #Analytics API via C#

Accessing the Google #Analytics API via C#

Google-Analytics-Logo

Say you want to import Google Analytics Data into a database, for display on your own admin system, or as an alert if you stop getting traffic. – here’s some code to do so in C#,

Grab a few packages from Nuget to get started:

Google.Apis and Google.Apis.Analytics.v3

First, off you need to authenticate against Google, you can do this in a number of ways but I found OAuth easiest.

string[] scopes = new string[] {
AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data
AnalyticsService.Scope.AnalyticsEdit, // Edit and manage Google Analytics Account
AnalyticsService.Scope.AnalyticsManageUsers, // Edit and manage Google Analytics Users
AnalyticsService.Scope.AnalyticsReadonly}; // View Google Analytics Data

var clientId = “xxxxxx.apps.googleusercontent.com”; // From https://console.developers.google.com
var clientSecret = “xxxxxx”; // From https://console.developers.google.com

// Could use Service account, if we don’t want the web-popup.

// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
},
scopes,
Environment.UserName,
CancellationToken.None,
new FileDataStore(“Daimto.GoogleAnalytics.Auth.Store”)).Result;

var service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = “Analytics API Sample”,
});

I’ve left out the client ID and Client Secret, you get these from your google developer console.

The Hierarchy of objects within Google Analytics is

Account > Property > View

So, you’ll need to enumerate each Account, Property and View to drill down to individual site statistics

ManagementResource.AccountSummariesResource.ListRequest list = service.Management.AccountSummaries.List();
AccountSummaries feed = list.Execute();

foreach(AccountSummary acct in feed.Items)
{
ManagementResource.WebpropertiesResource.ListRequest propList = service.Management.Webproperties.List(acct.Id);
Webproperties webProperties = propList.Execute();
var allProps = webProperties.Items.ToList();

……
}

This code enumerates each account, and each property within the account. Note that each call is limited to 1,000 records or so. I’m ignoring the case that you may have more than that.

Then to enumerate the views for each property – typically there may only be one, use this loop:

foreach (var lWeb in allProps)
{
ManagementResource.ProfilesResource.ListRequest viewList = service.Management.Profiles.List(acct.Id, lWeb.Id);
Profiles viewProperties = viewList.Execute();
var allViews = viewProperties.Items.ToList();
foreach (var lView in allViews)
{
…. store lWeb.Name & lView.Id
}
}

Now, for instance, if you wanted to get the number of unique sessions in the last month, given the View ID, then you use this

var strFrom = DateTime.Now.AddMonths(-1).ToString(“yyyy-MM-dd”);
var strTo = DateTime.Now.ToString(“yyyy-MM-dd”);
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(“ga:” + strView, strFrom, strTo, “ga:sessions”);
GaData result = request.Execute();

If result.Rows is null, then you’ve had no visitors in the month, otherwise result.Rows[0][0] indicates the number of visitors.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: