Google analytics reporting api using C#

In this blog post, we will be looking to get data from Google analytics using C#.

  • Add google analytics client library to the project using NuGet package manager.

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

  • You have to get API authentication using Google developer console.
  • Once you get authenticated and get the credentials needed, Google Analytics core reporting API will help us in querying the report’s data. Each query needs profile id, start date, end date and at least one metric. Optionally we can add, dimensions, filters, and segments to refine the query.
  • Profile id must start with ga:, for example, if your profile id is 8903066 then you would send ga:8903066
  • Date format can be YYYY-MM-DD or you can also give in dynamic dates like today, yesterday and NDaysAgo where N is the number.
  • Let us assume, we want to request the number of sessions for given data
    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();
  • If you want the same query between dynamic dates, the query would look like this:
DataResource.GaResource.GetRequest request = service.Data.Ga.Get("ga:8903098", "yesterday", "yesterday", "ga:sessions");
request.MaxResults = 1000;
GaData result = request.Execute();
  • Also, the maximum number of rows returned by request is set by using request.MaxResults. By default, it is 1000, but we can query up to 10000. If your request has more than 10000 rows then you might have to call the API using offset.
  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
   // 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)
   // 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)
        return null;
  • Here is how you can display the data:
    foreach (var headers in allData.ColumnHeaders) {
         Console.WriteLine( String.Format("{0} - {1} - {2}"
    foreach (List row in allData.Rows) {
         foreach (string col in row) {
                Console.Write(col + " ");  // writes the value of the column

    NOTE: Google states that data is not finished processing till 24 hours. If you request today or yesterday, the data may not be accurate.


Here is how you can fetch Google analytics data using C#.

Thanks for dropping by !! Feel free to comment to this post or you can also drop me an email at [email protected].