Google Analytics Core Reporting API with C# – Its all about the data baby! 31


[wp_ad_camp_5]
Google AnalyticsHave 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!

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


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.

31 thoughts on “Google Analytics Core Reporting API with C# – Its all about the data baby!

  • Lee Zoumas

    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!

  • Lee Zoumas

    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!

  • Senthil

    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.

      • Senthil

        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 …

  • Senthil

    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

  • Max Hurtado

    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.

  • Babu Kannan M

    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.

  • myke black

    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.

      • ibrahim

        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.

      • John

        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.

    • Linda Lawton Post author

      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.

  • Gabriel

    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?