DEV Community

chuac
chuac

Posted on

GA4 Data API with .NET

Our .NET 7 backend was querying Universal Analytics (UA) using Google.Apis.Analytics.v3 but as we drew closer to UA's shutdown date on July 1st 2023, we had to make the change to start querying our Google Analytics 4 (GA4) properties.

The package you'll need is Google.Analytics.Data.V1Beta - Not to be confused with Google.Apis.AnalyticsData.v1beta

Authenticating your client

Head here to follow the steps. After Step 1, you will have a credentials.json file which we will reference in our code soon.

Complete Step 2, to add the the service account that looks similar to quickstart@PROJECT-ID.iam.gserviceaccount.com to your GA4 property.

Now in your code, we will build the client and authenticate it using the credentials.json you created above. You are able to simply reference the JSON file from your code by setting CredentialsPath (and swap it out when deploying to different environments) however, we prefer swapping our environment dependent application settings (or secrets) as strings.

Luckily, the library accepts the JSON file as a JSON string. Simply JSON stringify the contents of your credentials.json and pass it to the client builder like so:

var analyticsDataClient = new BetaAnalyticsDataClientBuilder
{
    JsonCredentials = "JSON_STRINGIFY_YOUR_CREDENTIALS",
}
.Build();
Enter fullscreen mode Exit fullscreen mode

Using the client to get data

The possibilities are endless as to what dimensions/metrics/filters/date ranges you can do, with documentation of all schema very good.

Here's a simple example to get screen page views for particular page paths between "yesterday" and "today". You will need your GA4 Property ID (you can find this in "Property Settings" in GA, remember this is not your Measurement ID)

RunReportRequest request = new ()
{
    Property = "properties/" + "YOUR_GA4_PROPERTY_ID",
    Dimensions = { new Dimension { Name = "pagePath" }, },
    Metrics = { new Metric { Name = "screenPageViews" }, },
    Limit = 10000,
    DateRanges = { new DateRange { StartDate = "yesterday", EndDate = "today", }, },
    DimensionFilter = new FilterExpression()
    {
        Filter = new Filter()
        {
            FieldName = "pagePath",
            StringFilter = new StringFilter()
            {
                MatchType = StringFilter.Types.MatchType.Contains,
                Value = "deals/",
            },
        },
    },
};

var response = await analyticsDataClient.RunReportAsync(request);
Enter fullscreen mode Exit fullscreen mode

Note: Limitations with Realtime reports

There isn't 100% feature parity between UA Data API and this newer GA4 Data API. One dimension we were dependent on for Realtime reports was pagePath. You can recall above that it exists for normal reports but is missing for Realtime. There is an existing issue logged but with most recent activity being in 2022, I wouldn't count on that feature coming in anytime soon.

Top comments (0)