In this post, I will explain step-by-step how to get most viewed pages from google analytics using a dot net core console application.

1. Create and enable a project in the Google API console

Follow the steps using the setup tool to Create or Select a project, and then enable the API.

2. Generate service account credentials

In this step, we will generate a JSON file that represents the necessary credentials to access analytics information.

  • Open the Service Account. If no project is selected, a prompt will guide you to select one. If there is already a service account for your project it will be shown here.
  • Click 'CREATE SERVICE ACCOUNT' link
  • Complete a service account name, id, and description fields and hit 'Create' buttonExample ga service account 
  • Hit continue for the next optional step
  • The last step contains the 'Create key' menu. Click the 'Create key' button, select json option and click 'Create'. This action will download a JSON file that contains the key we need to securely access the reporting API. It is your responsibility to secure this file.

in the list of Service Accounts now should be another email formatted something like this: <SERVICE_ACCOUNT_NAME>@<PROJECT_ID>.iam.gserviceaccount.com. Make note of this email as we will need it to the next step.

3. Add the service account we created to google analytics account

  • Sign in Google Analytics
  • Open Admin menu, select your project, then click User Management under view settings. Please note that you can create the user even in a higher level such as Account or Property, but view level is enough for this case
  • Click the '+' button > Add Users to add a new user
  • Enter the email address of the service account we created in the previews step, uncheck 'Notify by email'.
  • Make sure only Read & Analyze permission is checked and then click Add.

With these steps in place, now we can start coding the project.

4. Create a .net core console application that will query the v4 of analytics reporting API

Open vs/vscode and create a new project using console application template. for this sample, I'm naming it AnalyticsReportingApi. We will need to install nugget packages offered by Google, so open package manager console and type:

Install-Package Google.Apis.AnalyticsReporting.v4

Create a settings file to hold some configurations, appsettings.json:

{
  "GoogleConfigFilePath": "C:\\eb\\ermir.net\\reporting-api-f2ec0991592c.json",
  "ApplicationName": "sporti-sot",
  "ViewId": "180984263",
  "Filter": "~/topic-",
  "PageSize": "5"
}
  • ApplicationName Get this value from the json file project_id value
  • ViewId Get this value from: Analytics > Account > Property > View > ViewSettings
  • Filter this is a represantation of the url structure we are looking to get measures for, ex we don't want to count the index page, or contact page, instead we want to query only the articles, and in my case the url is something like: /topic-<ARTICLE_ID>/ARTICLE_SERP
  • PageSize This is the total count of query results that we want to retrieve, default is 1000

Create a C# model class that will map into this json structure:

    public class AppSettings
    {
        public string GoogleConfigFilePath { get; set; }
        public int PageSize { get; set; }
        public string ApplicationName { get; set; }
        public string ViewId { get; set; }
        public string Filter { get; set; }
    }

Create a C# model class that maps the json structure of service account credentials (the file we downloaded from step 2)

    public class GoogleCredentialsModel
    {
        public string Type { get; set; }
        public string Project_id { get; set; }
        public string Private_key_id { get; set; }
        public string Private_key { get; set; }
        public string Client_email { get; set; }
        public string Client_id { get; set; }
        public string Auth_uri { get; set; }
        public string Token_uri { get; set; }
        public string Auth_provider_x509_cert_url { get; set; }
        public string Client_x509_cert_url { get; set; }
    }

PopularUrlService Add this C# class into your project. This will be responsible for retrieving data from GA report API


    internal List<(string, int)> GetParsedResult()
    {
        var response = QueryAnalyticsApi();
        if (response.Reports == null || response.Reports.Count == 0)
        {
            throw new Exception("Google query didn't respond with any result");
        }
        var items = new List<(string, int)>();

        var responseReport = response.Reports[0].Data;
        foreach (var item in responseReport.Rows)
        {
            var pageUrl = item.Dimensions.FirstOrDefault();
            var pageViews = item.Metrics.Select(x => x.Values.Select(v => v).FirstOrDefault()).FirstOrDefault();
            if (int.TryParse(pageViews, out var pageViewsNr))
            {
                items.Add((pageUrl, pageViewsNr));
            }
        }
        return items;
    }

    private GetReportsResponse QueryAnalyticsApi()
    {
        if (string.IsNullOrEmpty(_configs.GoogleConfigFilePath))
            throw new Exception("google config file path is not provided");

        string json = System.IO.File.ReadAllText(_configs.GoogleConfigFilePath);
        var credentialsObj = JsonConvert.DeserializeObject<GoogleCredentialsModel>(json);

        var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(credentialsObj.Client_email)
        {
            Scopes = new[] { AnalyticsReportingService.Scope.AnalyticsReadonly }
        }.FromPrivateKey(credentialsObj.Private_key));

        var baseClientInitializer = new BaseClientService.Initializer
        {
            HttpClientInitializer = xCred,
            ApplicationName = _configs.ApplicationName
        };

        using (var svc = new AnalyticsReportingService(baseClientInitializer))
        {
            var pageViewsRequest = new ReportRequest
            {
                ViewId = _configs.ViewId,
                Dimensions = new List<Dimension> { new Dimension { Name = "ga:pagePath" } },
                Metrics = new List<Metric> { new Metric { Expression = "ga:pageviews", Alias = "PageViews" } },
                OrderBys = new List<OrderBy> { new OrderBy { FieldName = "ga:pageviews", SortOrder = "descending" } },
                HideValueRanges = true,
            };

            if (StartDate.HasValue && EndDate.HasValue)
            {
                pageViewsRequest.DateRanges = new List<DateRange>() { new DateRange() { StartDate = StartDate.Value.ToString("yyyy-MM-dd"), EndDate = EndDate.Value.ToString("yyyy-MM-dd") } };
            }
            if (!string.IsNullOrEmpty(_configs.Filter))
                pageViewsRequest.FiltersExpression = $"ga:pagePath={_configs.Filter}";
            if (_configs.PageSize != 0)
                pageViewsRequest.PageSize = _configs.PageSize;

            GetReportsRequest getReport = new GetReportsRequest()
            {
                ReportRequests = new List<ReportRequest>
                {
                    pageViewsRequest
                }
            };

            var response = svc.Reports.BatchGet(getReport).Execute();
            return response;
        }
    }

You can use different dimensions or metrics, according to your needs. For example, in here I use the default filter for dates, which is last 7 days, starting from yesterday. You could use custom start/end date when initializing PopularUrlService and then get the result for specified dates.

To view the full source of this demo visit : https://github.com/ermirbeqiraj/AnalyticsReportingApi