Shawn Miller

Consuming the Google Analytics API with .NET

December 29, 20099:07 PM

The Google Analytics API gives you read-only access to the data kept in a Google Analytics profile. Essentially every piece of information that can be displayed in the Google Analytics web interface is accessible through the API in the form of GData feeds.

If you want to consume the Google Analytics API from .NET you essentially have two options. You can use the GData .NET Client library (which doesn't yet officially list Google Analytics as a supported service, but if you browse the source you'll find it). Or you can roll up your sleeves and issue the HTTP GETs and POSTs yourself.

If you're doing the later you might find that this little bit of C# we created could save you some time.

using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web;
using System.Xml;

namespace GoogleAnalytics
{
   
public static class Client
   
{
      
public static string GetAuthorizationToken(string email, string password)
      {
         
using (var webClient = new WebClient())
         {
            
var nameValueCollection = new NameValueCollection();
            nameValueCollection.Add(
"Email", email);
            nameValueCollection.Add(
"Passwd", password);
            nameValueCollection.Add(
"service", "analytics");

            var response = webClient.UploadValues("https://www.google.com/accounts/ClientLogin", nameValueCollection);
            
var values = Encoding.Default.GetString(response).Split('\n');

            return values.First(value => value.StartsWith("Auth=")).Replace("Auth=", String.Empty);
         }
      }

      public static SyndicationFeed GetAccountFeed(string authorizationToken)
      {
         
using (var webClient = new WebClient())
         {
            webClient.Headers.Add(
"GData-Version", "2");
            webClient.Headers.Add(
"Authorization", String.Format("GoogleLogin Auth={0}", authorizationToken));

            var response = webClient.DownloadString("https://www.google.com/analytics/feeds/accounts/default");

            return SyndicationFeed.Load(XmlReader.Create(new StringReader(response)));
         }
      }

      public static SyndicationFeed GetDataFeed(string authorizationToken, string profileId, DateTime startDate, DateTime endDate, string metrics, string dimensions, string sort, int? maxResults)
      {
         
using (var webClient = new WebClient())
         {
            
var query = HttpUtility.ParseQueryString(String.Empty);
            query.Add(
"ids", profileId);
            query.Add(
"start-date", startDate.ToString("yyyy-MM-dd"));
            query.Add(
"end-date", endDate.ToString("yyyy-MM-dd"));
            query.Add(
"metrics", metrics);

            if (!String.IsNullOrEmpty(dimensions))
            {
               query.Add(
"dimensions", dimensions);
            }

            if (!String.IsNullOrEmpty(sort))
            {
               query.Add(
"sort", sort);
            }

            
if (maxResults.HasValue)
            {
               query.Add(
"max-results", maxResults.Value.ToString());
            }

            var uri = new UriBuilder("https://www.google.com/analytics/feeds/data");
            uri.Query = query.ToString();

            webClient.Headers.Add("GData-Version", "2");
            webClient.Headers.Add(
"Authorization", String.Format("GoogleLogin Auth={0}", authorizationToken));

            var response = webClient.DownloadString(uri.Uri.AbsoluteUri);

            return SyndicationFeed.Load(XmlReader.Create(new StringReader(response)));
         }
      }
   }
}