[wp_ad_camp_5]
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!
Prerequisites
Make sure your project is at least set to .Net framework 4.0 or 4.5.
Add the following NuGet Package
NuGet Google.Apis.Analytics.v3 Client Library
PM> Install-Package Google.Apis.Analytics.v3
This will automaticly install Google.Apis and Google.Apis.Auth which you will also need.
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;
Google Developers console
This tutorial assumes that you have already created a project on Google Developers console and have enabled the Google Analytics API, if you havent I have a tutorial series for beginning Google development which will walk you though that step. Beginning Google Development.
Analytics Service
This tutorial also assumes that have 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.
Google Analytics Core Reporting API
The Google Analytics Core Reporting API allows you to query report data. Each query requires a view (profile) ID, a start and end date, and at least one metric. You may also supply additional query parameters such as dimensions, filters, and segments to refine your query.
Required values
Profile Format
When querying the Google Analytics Reporting api the profile id must start with ga: For example if your profile(view) id is 8903098 then you would send ga:8903098.
Date Format
Start date and end date are required fields this tells the system what dates you would like to see your reporting data for. The format must be YYYY-MM-DD, you can make requests with dynamic dates. Today, yesterday or NDaysAgo (where N is a number) . Using dynamic dates can be useful if you just want to see last weeks data for example.
Metrics
You must request at least one metric, more then one is separated by a comma. You can find a list of metric either by using the Metadata api or by checking the Dimensions & Metrics Reference.
Basic Query
A very basic request would be to just check the number of sessions for a given date.
DataResource.GaResource.GetRequest request = service.Data.Ga.Get("ga:8903098", "2014-01-01", "2014-01-01", "ga:sessions"); request.MaxResults = 1000; GaData result = request.Execute();
Again you can do the same using dynamic dates.
DataResource.GaResource.GetRequest request = service.Data.Ga.Get("ga:8903098", "yesterday", "yesterday", "ga:sessions"); request.MaxResults = 1000; GaData result = request.Execute();
Note: Google states the data is not finished processing for at least 24 hours. If you request today or yesterday the numbers may not be correct.
Next page
The maximum number of rows returned by a request is set by using request.MaxResults. By default it is 1000 you can set it as high as 10000. If your request does return more rows then you will need to get the next set. The following code will help you with that. It continues requesting more data until it has it all. allData will then contain all the rows.
try { GaData result = request.Execute(); List allRows = new List(); //// Loop through until we arrive at an empty page while (result.Rows != null) { //Add the rows to the final list allRows.AddRange(result.Rows); // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (result.NextLink == null) { break; } // Prepare the next page of results request.StartIndex = request.StartIndex + request.MaxResults; // Execute and process the next page request result = request.Execute(); } GaData allData = result; allData.Rows = (List)allRows; } Catch (Exception ex) { Console.WriteLine(ex.Message); return null; }
Now if you check the allData variable you will find that all of your rows are added to the allData.Rows. I have create a method out of this myself. check ProcessResults
Displaying the data
[wp_ad_camp_3]
The name of each column can be found in the ColumnHeaders and each row of data is found in Rows.
foreach (var headers in allData.ColumnHeaders) { Console.WriteLine( String.Format("{0} - {1} - {2}" ,headers.Name ,headers.ColumnType ,headers.DataType)); } foreach (List row in allData.Rows) { foreach (string col in row) { Console.Write(col + " "); // writes the value of the column } Console.Write("\r\n"); }
Advanced Query
dimensions
A list of comma-separated dimensions for your Analytics data, such as ga:browser,ga:city.
request.Dimensions = "ga:browser,ga:city";
samplingLevel
Sometimes depending upon the request Google Analytics API can return Sampled data. Sampled data is correct but not exactly 100% accurate. You can change the sampling level if you wish.
The desired sampling level. Allowed Values:
•DEFAULT — Returns response with a sample size that balances speed and accuracy.
•FASTER — Returns a fast response with a smaller sample size.
•HIGHER_PRECISION — Returns a more accurate response using a large sample size, but this may result in the response being slower.
request.SamplingLevel = DataResource.GaResource.GetRequest.SamplingLevelEnum.DEFAULT;
max-results
The maximum number of rows to include in the response.
request.MaxResults = 1000;
Conclusion
You should now understand how to access the Google Analytics Reporting API with an authenticated user. We have looked at how make a basic request with just a single metric for a specific date, we have also looked at using dynamic dates. You should understand what Sampling is and how to change the sampling level.
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 the Reporting API with Google Analytics. DaimtoAnaltyicsReportingHelper.cs
Can I just say thank you for posting these tutorials, you’ve saved me a ton of time. I’ve managed to get the real time data and core data I need in just a couple of hours.
I am very glad to hear that you enjoyed the tutorial. Please remember to Share it 🙂
This is very helpful thank you!
One question, I am trying to implement the Next page functionality. In what context is that code sample you provided. It is part of a function of some sort? Also, I get an exception on the…
List allRows = new List();
… line. What type of List is it?
Thanks again!
You are right it is part of a function. The full function returned a Gadata object. check ProcessResults I will fix the tutorial so it is more clear.
Cool thank you. The problem I had was I never set the start index to 1 so i was in an infinite loop.
Thanks so much.. you have no idea how helpful this was!
thanks a lot for this post. this helped me so much.
But when i execute the below query, i get an error saying “missing ClientServiceRequest.cs” .. Please assist ,, Thanks again.
request.MaxResults = 1000;
request.Dimensions = “ga:dimension2,ga:source,ga:medium,ga:campaign,ga:keyword,ga:date,ga:hour”;
GaData result = request.Execute();
Locating source for ‘c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\test\default\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs’. Checksum: MD5 {42 80 5 5a 5a 90 1f 2c df 84 5a 16 b5 17 61 1a}
The file ‘c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\test\default\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs’ does not exist.
sounds like your having an issue with the DLLs make sure they are all set to copy to the bin dir.
thanks for your reply. I used Nuget to load all of them using “Install-Package Google.Apis.Analytics.v3” command.
I refreshed it again, but still i am getting the same issue. May be i need to get the source from somewhere ? Please advice …
I guess it is the issue on the file location. I use Nuget to get all the DLL’s , all the DLL’s are in location folder under “Packages” folder.
But when the package gets executed, it is looking for the DLL’s in C:\Code\Google.Com……….” …
Any thoughts will be helpful … Thanks
Thanks heaps for this, minor correction the PM install..
Install-Package Google.Apis.Analytic.v3 should be: Install-Package Google.Apis.Analytics.v3
Thank you very much, I fixed the section and added a few links to Nuget package this should help if its every changed.
Thanks for you post. I really help me very much!
I have a question. How can I make de Query in order to insert filters (for example the page name).
I’m using the DaimtoAnaltyicsReportingHelper.OptionalValues.Filter but the result is null.
Can you help me with an example, please?
Thanks in advance.
the best place to test filters and all requests really is the query explorer. Once you get it working you can just move to the api.
Hi Linda, Could please provide me a complete working code to fetch google analytics core reporting data, would be helpful me to integrate those data to my datawarehouse.
doesnt get much fresher then this one https://github.com/LindaLawton/Google-Dotnet-Samples/tree/master/Google-Analytics, if your integrating into data warehouse have you considered the SSIS task? https://www.daimto.com/ssis-data-reader-for-google-analytics/
Its very article and even better than Google Officiel Documentation.
Excellent work! I’ve been trying for days to figure out a very simple way to display just a list of users for each day of the previous month and show in a graph. Keep going round and round the google API’s but there are no simple instructions for doing it using asp.net. Using some of your code I can now generate some javascript to feed into Chart.js to show the graph. Took me a little while to figure out I had to set the dimensions to “ga:day” to show data for each day of the month.
Hello Linda Lawton, can you explain to me this question.
i set to request.MaxResults = 1000; but why api return only 30 record?
That is most likely because there is only 30 results to your request.
Thank you for your reply. bu it is not possible. because i can see 90 days on my analytics account yet. But when i use api i can not get my 90 days report. An example i run this code;
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(“ga:21569768”, “2015-08-01”, “2015-11-13”, “ga:sessions, ga:pageviews, ga:newVisits, ga:percentNewSessions, ga:bounceRate”);
request.Dimensions = “ga:day”;
request.MaxResults = 1000;
request.StartIndex = 1;
GaData result = request.Execute();
var allRows = new List<IList>();
………………………
………………………
and it takes me only 30 rows. some thing is wrong. please check this code on your demo.
that’s probably because there are only 30 rows if there is no data in one of those metrics then you are only going to get the days where there are data.
it’s true. in query browser return only 31 record always. if you want 1000 rows, you must write diffirent methods. your library must be update Linda.
If you set maxrows of rows 1000 and there are 1000 rows they will be returned. However if there are only 31 rows then you are only going to see 31 rows.
How can I retrieve 30 metrics in a single api call? Google limits this to 10 currently.
make additional requests. You cant get more then 10 in a single request.
Thank you so much!!!!!!!!!!!!!!!!!!!!!!!
Very useful, exactly what i need. Straightforward solution and easy to understand.
i have error in request.execute. object reference null, i pass all parameter and all value as you define. but its still not working
I recommend you copy your code and ask a question on Stackoverflow.com include all your code. Tag it Google-api-dotnet-client I should spot it and be able to help you debug it.
Hi Linda
I would like to add functionality to my crowdfunding website where the campaigner can see google analytics reports for their own specific campaign/page. Which tutorial or sample would guide me into achieving that?
I found a solution. Just in case someone has a similar requirement, you can use the Embed API – https://developers.google.com/analytics/devguides/reporting/embed/v1/
Cheers