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
- Google Analytics API Introduction
- Google Analytics API Authentication with C# OAuth2 vs Service Account
- Google Analytics Management API with C#Accounts, Web Properties and views(Profiles)
- Google Analytics Management API with C# – Advanced
- Google Analytics Management API with C# – Upload
- Google Analytics Meta-Data API with C# – Showing current dimensions and metrics
- Google Analytics Real-Time API with C# – Whats happening now!
- 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
Usings
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;
Authentication
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.
[wp_ad_camp_1]
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 } Console.Write("\r\n"); }
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)); }
Conclusion
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
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.
I am new in this kind of apis and the tutorial is soooo clear.
Thank you so much! 🙂
Hi,
I got below exception while using service account. Please help.
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:”invalid_grant”, Description:””, Uri:””
invalid_grant has two causes that i am aware of.
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.
Hi Linda,
I’m accessing google analytic from my local machine,
So? What time is it on your local machine is it correct or not?
Hi Linda,
How can i check our system sync with ntp server time.
To start with look at your clock is the time correct? You can read about NTP here
Hi Linda,
I have sync server time with ntp server time,but still i am facing this issue.
I don’t know what else your problem could be. Its probably not anything to do with the refresh-token limit because you are using a service account.
Sorry I couldn’t be of more help. If you find the problem let me know and I will update the tutorial so that if anyone else has the problem they will be able to fix it.
Hi Linda,
Thanks for your help
It’s working now with oauth2 authentication instead of service account.
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?
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)?
I think you missed a section of the tutorial.
from where I get the profil id ?
Profile id is the same as view id. They renamed it a few years ago.
Hi Linda,
Great Code. I tried and it worked. Thanks for Sharing
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 https://www.nuget.org/packages/Google.Apis.analytics.v3/
Hi pop up a question on and i would be happy to have a look at your code.