Google Analytics Real-Time API with C# – Whats happening now! 19

Google Analytics
Have you been trying to connect your website or application to Google Analytics? Would you like to be able to show your users Google Analytics data for your website?   If you are you trying to work with the Google Analytics API in C# .net I might be able to help.   In this tutorial series we will be looking into how to connect to Google Analytics API using OAuth2, as well as a service account. I will show you how to get a list of the users Accounts to display to them from the Google Analytics Management API. Using the Meta-data API you will be able to get a full up to date list of the current available metrics and dimensions to display to your users. Finally we will look at getting data back from Google Analytics by using either the Real-time API or the Core reporting API.

Google Analytics API – Seven part Tutorial Series

  1. Google Analytics API Introduction
  2. Google Analytics API Authentication with C# OAuth2 vs Service Account
  3. Google Analytics Management API with C#Accounts, Web Properties and views(Profiles)
  4. Google Analytics Management API with C# – Advanced
  5. Google Analytics Management API with C# – Upload
  6. Google Analytics Meta-Data API with C# – Showing current dimensions and metrics
  7. Google Analytics Real-Time API with C# – Whats happening now!
  8. Google Analytics Core Reporting API with C#  – Its all about the data baby!

Project Setup

Make sure your project is at least set to .net 4.0.

Add the following NuGet Package

PM> Install-Package Google.Apis.Analytic.v3


You will probably need most of these using’s

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.Apis.Analytics.v3;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using System.IO;


This tutorial assumes that you have already read the tutorial about Google Analytics API Authentication with C#. I will not be going into how to create a valid Analytics service if you haven’t created one already please go read that tutorial then come back here.


Requesting Data from Real-time Google Analytics API With C#

The Real-time Google Analytics API shows you what is going on right now. Because of that we don’t need to send it information about when we want to see data for it is always the same its NOW.

Real-time API Dimensions and Metrics

The dimensions and metrics available for querying the Real-time API are not available though the meta-data API (a feature request for this has been submitted). That being said the list of dimensions and metrics for use with the Real-time API are different then the ones for the Core Reporting API. You can find that list here Dimensions & Metrics Reference.  As you can see its very limited.    The reason for this limitation is probably because a lot of the dimensions and metrics available with the Core Reporting API are derived only after Google has processed the data it received from your website or application.   Google needs time to process that data, official Google says that the data is done processing after 24 – 48 hours.

Requesting Data from the Real-time Google Analytics API

We use the service that we created in the Authentication tutorial to make a GET call to the Google Analytics Real-time API. The Get request requires that you send it a profile id, and a comma separated list of metrics you would like to request. The profile id needs to start with “ga:” For example if your profile id was 78110423 then you would send ga:78110423.

DataResource.RealtimeResource.GetRequest request = service.Data.Realtime.Get(String.Format("ga:{0}", profileId), "rt:activeUsers");
RealtimeData feed = request.Execute();

As you can see this returns an object of RealtimeData resource.

There are two things that will be important for you here:

  • columnHeaders – Column headers that list dimension names followed by the metric names. The order of dimensions and metrics is same as specified in the request.
  • rows – Real time data rows, where each row contains a list of dimension values followed by the metric values. The order of dimensions and metrics is same as specified in the request.

Displaying Google Analytics Real-time API data

Each of the rows returned is a list of strings containing the value for each of the columns.

 foreach (List  row in realTimeData.Rows) 
     foreach (string col in row) 
         Console.Write(col + " ");  // writes the value of the column

Displaying Google Analytics Real-time API columnHeaders

I find the column headers very useful, the column headers not only tell you the name of the column but also the Datatype of that column and if it is a Dimension or a metric.

foreach (var headers in realTimeData.ColumnHeaders) 
   Console.WriteLine( String.Format("{0} - {1} - {2}", headers.Name ,  headers.ColumnType ,headers.DataType));


You should now understand how to access the Google Analytics Real-Time API with an authenticated user. Join me for the next tutorial where we will look at how to get data from the Core reporting API for an authenticated Analytics Service.

If you had any problems with this tutorial you can check the a sample project for working with Google Analytics API on GitHub as part of the Google-Dotnet-Samples project. With in that project you will find a helper class for Real-time API with Google Analytics. DaimtoAnaltyicsRealTimeHelper.cs

About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

19 thoughts on “Google Analytics Real-Time API with C# – Whats happening now!

  • Veerkumar Patil

    I was looking for simple post that will help me to retrive the google analytics real time data using API calls. Thanks a lot.Very neat explaination.
    Now i can retreive the data easily.

  • Fahim


    I got below exception while using service account. Please help.

    Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:”invalid_grant”, Description:””, Uri:””

    • Linda Lawton Post author

      invalid_grant has two causes that i am aware of.

      • Your server’s clock is not in sync with NTP. (Solution: check the server time if its incorrect fix it. )
      • The refresh token limit has been exceeded. (Solution: Nothing you can do they cant have more refresh tokens in use)
        Applications can request multiple refresh tokens. For example, this is useful in situations where a user wants to install an application on multiple machines. In this case, two refresh tokens are required, one for each installation. When the number of refresh tokens exceeds the limit, older tokens become invalid. If the application attempts to use an invalidated refresh token, an invalid_grant error response is returned. The limit for each unique pair of OAuth 2.0 client and is 25 refresh tokens (note that this limit is subject to change). If the application continues to request refresh tokens for the same Client/Account pair, once the 26th token is issued, the 1st refresh token that was previously issued will become invalid. The 27th requested refresh token would invalidate the 2nd previously issued token and so on.
  • FCU

    I am following this example. Works good until I get to the foreach (List row in feed.Rows) .Net gives me a Error Using the generic type ‘System.Collections.Generic.List’ requires 1 type arguments . Ideally I would like to know how to go about getting the # of realt time users for each of my properties in my profile. Can you help me understand what I might be missing?

  • Anh Tran

    What is “service” in service.Data.Realtime.Get(String.Format(“ga:{0}”, profileId), “rt:activeUsers”);?
    You have no declareation. Could you show full code (class)?

  • Sachin

    hie i was trying to execute the code but its not working its giving me error

    var request = service.Realtime.Get(ids, metrics);

    ‘AnalyticsService’ does not contain a definition for ‘Realtime’ and no accessible extension method ‘Realtime’ accepting a first argument of type ‘AnalyticsService’ could be found (are you missing a using directive or an assembly reference?)

    Even i installed the pacakge