How to get page views and events data from GA4 in .NET

Google Analytics 4 has replaced Universal Analytics and I am sure you have made the switch as your Universal Analytics properties stopped processing any information starting July 1, 2023.

Since GA4 is a new and enhanced platform with new API and libraries, our existing approach of Read Google Analytics reports using C# console app would no longer work with GA4.

Let's go through step-by-step process of configuring API access, setting up credentials and utilizing the .NET client library to fetch reports from GA4.

Setup a new Google Cloud project and enable Google Analytics Reporting API

Go to https://console.cloud.google.com/

Login with your Google credentials

Create a new project. Let's call it "Get GA4 Report Data".

Once the project is created, go to Enabled APIs & services section and choose +ENABLE APIS AND SERVICES

Look for Google Analytics Reporting API and enable it.

Now setup credentials for API access

Select Service Account option.

Give it name. Here I have named it as "GA4 Service Account".

Create a key for Service Account

This will create and download the JSON key file which we will be using later in our project.

Open the downloaded JSON Key File in a text editor and copy the value of client_email key.

Now provide user access to this email to your GA4 property.

Go to Admin section of your GA4 property and Property Access Management link.

Viewer role should be sufficient to access the report.

Our project and credentials setup are complete.

Create a new C# project

Create a new C# console application.

Install Google.Analytics.Data.V1Beta nuget package. The package is still in beta phase, so select Include prerelease option to get the latest package version.

Rest of the code is available at https://github.com/kumarvikram/ga-reporting-dotnet-framework

Please let me know in the comments if you have any questions.