Analytics API Example (C#/CSharp/ASP.NET)

This CSharp (C#/ASP.NET) code snippet demonstrates, how you can access Google Analytics statistics by using the Analytics API client library provided by Google.

As the Google Analytics API does not allow login/password authentication anymore, the example shows how the authentication with OAuth is done. With OAuth, the user is redirected to an external authentication website hosted by Google. On this website, the user can login and afterwards allow access for your web application to use the Google Analytics API. Afterwards the user is redirected back to your website with an authentication parameter, which is then used by your ASP.NET application to authenticate Analytics API access.

In order to use the Analytics API as a developer, you have to complete the following steps first:

  • Create a new account on the Google API Console https://code.google.com/apis/console/
  • Activate the Analytics API under the menu called services
  • Create a new web application Client ID under the menu point API Access and provide the corresponding URL of your web application as Redirect URI (the URL where Google redirects the user back after successful authentication, while passing the authentication code).
  • Note the Client ID and Client Secret for later usage in your program code
  • Download and extract the Google APIs Client Library for .NET
  • Copy all DLL files from the /lib/ subdirectory into the /bin/ subdirectory of your ASP.NET web application
  • Copy the Google.Apis.Analytics.v3.dll from the /Services/AnalyticsService/ subdirectory into the /bin/ subdirectory of your ASP.NET web application


Afterwards you can directly use the provided example code below to access Analytics statistics via the Analytics API.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using DotNetOpenAuth.OAuth2;
using DotNetOpenAuth.Messaging;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis;
using Google.Apis.Util;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;


public partial class _Report : System.Web.UI.Page
{
    private string ClientID = "<your-client-id>";
    private string ClientSecret = "<your-client-secret>";

    private AnalyticsService _service;
    private OAuth2Authenticator<WebServerClient> _authenticator;
    private IAuthorizationState _state;

    protected void Page_Load(object sender, EventArgs e)
    {
      if (_service == null)
      {
          _service = new AnalyticsService(_authenticator = CreateAuthenticator());
      }

      // check if OAuth2 authentication code was passed
      if (HttpContext.Current.Request["code"] != null)
      {
          _authenticator.LoadAccessToken();
      }

      if (!IsPostBack)
      {
        // get analytics profiles in account
        Profiles myProfiles = _service.Management.Profiles.List("~all", "~all").Fetch();

          if (myProfiles.Items.Count > 0)
          {
              // get sample statistics for first profile found
              var request = _service.Data.Ga.Get(
                  "ga:" + myProfiles.Items[0].Id, 
                  "2012-06-01", // start date 
                  "2012-06-30", // end date
                  "ga:visitors,ga:pageviews" // metrics to include in report 
                  );

              request.Dimensions = "ga:date";
              //request.Filters = "";
              request.Sort = "ga:date";
              request.StartIndex = 1;
              request.MaxResults = 500;

              GaData results = request.Fetch();

              // do whatever you like with the report data
          }
      }
    }

    private IAuthorizationState AuthState
    {
        get
        {
            return _state ?? HttpContext.Current.Session["AUTH_STATE"] 
                as IAuthorizationState;
        }
    }

    private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
    {
        WebServerClient myWebServerClient = 
            new WebServerClient(GoogleAuthenticationServer.Description);
        
        myWebServerClient.ClientIdentifier = this.ClientID;
        myWebServerClient.ClientSecret = this.ClientSecret;

        OAuth2Authenticator<WebServerClient> myOAuth2Authenticator = 
            new OAuth2Authenticator<WebServerClient>(myWebServerClient, GetAuthorization);
        
        return myOAuth2Authenticator;
    }

    private IAuthorizationState GetAuthorization(WebServerClient myWebServerClient)
    {
        // if user already authenticated => return state
        IAuthorizationState state = AuthState;
        
        if (state != null)
        {
            return state;
        }

        // if authorization request already in progress
        state = myWebServerClient.ProcessUserAuthorization(
            new HttpRequestInfo(HttpContext.Current.Request)
        );
        
        if (state != null && (!string.IsNullOrEmpty(state.AccessToken) 
            || !string.IsNullOrEmpty(state.RefreshToken)))
        {
            HttpContext.Current.Session["AUTH_STATE"] = _state = state;
            return state;
        }

        // otherwise start new authorization request for analytics scope
        string[] scopes = new string[] { 
            "https://www.google.com/analytics/feeds/", 
            "https://www.googleapis.com/auth/analytics.readonly" };

        OutgoingWebResponse response = 
            myWebServerClient.PrepareRequestUserAuthorization(scopes);
        
        response.Send();
        
        return null;
    }
}