Get most visited pages of your website from Google Analytics using C#

List most visited website pages from Google analytics in your .NET application code

If you have a website like this one with articles and you would like to suggest most visited articles to your visitors, there are few ways to do this. One of them is definitely a custom solution that can track and store count of every visit per page you have, or without any re-inventing of wheel you can just hook to Google Analytics API to pull the data. That is of course in case you are using Google Analytics and have it setup on your website. I cannot really imagine anyone not having Google Analytics on their website to track the visits and interests of the visitors.

Let's assume you have Google Analytics on your website and you are using it for quite some time. This means you already have the visits data collected by Google Analytics and you can access them from GA Dashboard.

First thing we are going to do is to query this data from Google API explorer which is part of Google Cloud Dashboard. If you do not have Google Cloud account, you can easily create it using the same account you are using fro your Google Analytics. Once you have Google Cloud account. login to dashboard and let's configure few things before we dig into coding.

Adding Google Analytics API and querying it

First thing you have to do once you sign in to Google Cloud dashboard is to create a new project. Project is kind of workspace where you are going to enable different APIs to integrate with.

New Project

Pick your project name and hit CREATE button. It will take few seconds until your project is created and than you can select it from projects list (if you have one project it will be preselected for you automatically after creation) and continue setting it up for Google Analytics API consuming.

Second thing you have to do after creating a project is to enable Google Analytics API to be used in your project. You can quick search APIs & Services in Cloud Dashboard search filed or just navigate to https://console.cloud.google.com/apis/dashboard. When APIs & Services dashboard loads, click ENABLE APIS AND SERVICES to enable Google Analytics API to your project.

Find Analytics API and click ENABLE button.

Enable Ga

Once you have Analytics service enabled, you can open the API Explorer from the APIs Dashboard and try out analytics.data.ga.get method (https://developers.google.com/apis-explorer/?hl=en_US#p/analytics/v3/analytics.data.ga.get). You will get the following UI loaded for the API call. Fill the form with the data as on the image below and hit "Authorize and execute" button to get the JSON response.

Api Explorer

For the ids filed value, use your Google Analytics view id you have setup fro your website. This option is available from Google Analytics dashboard, so you might have to login to Google Analytics and fetch it from there in order to run this API call.

Note

API call from API Explorer will only work if your Google Cloud account is authorized to access Google Analytics. If this is not the case, then add your account (email address) to members list from Google Analytics Admin section

As a resut of this API call you will get a JSON response which consists of lots of metadata including your query options, but what is importan for you is rows property. This portion of JSON response contains tha data you requested with dimensions parameter.

In out case this will be tha path, page title and number of page view.

If you need some more data to be extracted from Google Analytics, you can check Dimensions & Metrics reference page https://developers.google.com/analytics/devguides/reporting/realtime/dimsmets/ where you can find extact dimension names you can use in your API queries. I usually check my queries with API Explorer before I write any code which eventually reduces my debug time of the code because same parameters will be used from the code to acquire the data in our application from Google Analytics.

Setting Service Account and credentials

Nope, we are still not at the coding part. In order for your application to access the API it has to be authenticated but since it is not an actual person, you cannot use use consent page to dothis. Instead you can use ServiceAccount from your Google Cloud Project. You can create Service Account Key from the APIs & Services Dashboard from Credentials section.

Qa Credentials

For the account role choose Monitor Admin. This will allow service account to ave read permissions to all currently enabled service and as well to the ones you might add later to your project. Private key in P12 or JSON format will be offred to you to download after creatin of the account.

You can use both P12 and JSON but make sure you save them somwhere safely because you are going to need it in your code to authenticate your application to execute API query. How to use P12 certificate to authenticate as a service account from your application you acn find in the article Google Service Account authentication in .NET, but there will be code snippets in this article provided for both P12 and JSON service account key authentication in this article.

Create Service Account

Finally, you need to add your service account to members from Google Analytics Dashboard. Login to Google analytics, select your webiste (in case you have mutliple) and open Admin section. In Adnim section, got to User Management and add your service account email to the list.

Ga Permission

Finally, we are ready to jump to Visual Studio and start writing our Google ANalytics API client to pull most visited pages of or website.

Accessing Google Analytics API from C# code

We are ready to invoke Google Analytics API from our code now. To use Google API client for making the calls we need to add nuget packages to our project:

Ga Nuget

After adding the NuGet packages, we need to authenticate our application using previously created service account credentials in Cloud Console. Depending on which format of private key we picked when we created Service Account, JSON or P12, it will matter ho will we load credentials.

The following snippet will create credentials from key in JSON format:

        static GoogleCredential GetJsonCredential(string jsonFilePath)
        {
            GoogleCredential credential;
            using (Stream stream = new FileStream(jsonFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                credential = GoogleCredential.FromStream(stream);
            }

            string[] scopes = new string[] {
                    AnalyticsService.Scope.AnalyticsReadonly
                    };
            credential = credential.CreateScoped(scopes);
            return credential;
        }

    

All you need to pass to the method is JSON key file path to load credentials from. On the other hand if you are using P12 key for your service account, the following method will instantiate credentials object instance for API call authentication.

        static ServiceAccountCredential GetP12Credential(string p12FilePath, string accountEmail)
        {
            using (var certificate = new X509Certificate2( p12FilePath, "notasecret", X509KeyStorageFlags.Exportable))
            {
                var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(accountEmail)
                {
                    Scopes = new[] {
                        AnalyticsService.Scope.AnalyticsReadonly

                    }
                }.FromCertificate(certificate));

                return credential;
            }
        }

    

For P12 format key we need to supply the service account email address to instantiate credentials object which we'll use for the API request authentication. The following code uses JSON key format to instantiate credentials and make the API call identical to the one we have done using the API Explorer

            var credential = GetJsonCredential(Path.Combine(Directory.GetCurrentDirectory(), "xxxxxx-xxx-xxxxxx-xxxxxxxxxx.json"));

                using (var service = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "My Application Name",
                }))
                {
                    var apiRequest = service.Data.Ga.Get(
                         ids: "ga:xxxxxxxx",
                         startDate: "7daysAgo",
                         endDate: "today",
                         metrics: "ga:pageviews"
                         );
                    apiRequest.MaxResults = 10;
                    apiRequest.Dimensions = "ga:pagePath,ga:pageTitle";
                    apiRequest.IncludeEmptyRows = false;
                    apiRequest.Sort = "-ga:pageviews";
                    var data = apiRequest.Execute();

                    var result = data.Rows.Select(r => new
                    {
                        PagePath = r[0],
                        PageTitle = r[1],
                        ViewCount = int.Parse(r[2])
                    });
            }

    

You probably noticed that the parameters in the code are also the same as the ones entered in the API Explorer. In the end rows are transformed to a collection of anonymous type instances which are a lot more easier and convenient to use in the code later on than raw elements.

Note

Invoking this code on the request in web application may impact significantly page load time. It also can cause quota of the API endpoint to be reached. Because of these reasons it is recommended to cache it. For this purpose you can use Quartz and or any other scheduling library to run new content fetch from Google API

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform includion ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article