Skip to content

Instantly share code, notes, and snippets.

@abfo
Created May 6, 2023 19:19
Show Gist options
  • Save abfo/7b43eb74217f00dd26e4886604c288cf to your computer and use it in GitHub Desktop.
Save abfo/7b43eb74217f00dd26e4886604c288cf to your computer and use it in GitHub Desktop.
Very simple GA4 API example in C#. See https://ithoughthecamewithyou.com/post/migrating-a-c-integration-from-ga3-to-ga4 for details.
// uses Google.Analytics.Data.V1Beta from NuGet
// credentials from Google cloud project authentication export
// GA4 Profile ID from GA4 Admin
var client = new BetaAnalyticsDataClientBuilder
{
CredentialsPath = "PathToCredentials.json"
}.Build();
RunReportRequest request = new RunReportRequest
{
Property = "properties/***YOURGA4PROFILE***" ,
Metrics = { new Metric { Name = "totalUsers" }, },
DateRanges = { new DateRange
{
StartDate = DateTime.UtcNow.AddDays(-31).ToString("yyyy-MM-dd"),
EndDate = DateTime.UtcNow.AddDays(-1).ToString("yyyy-MM-dd") },
},
};
RunReportResponse response = client.RunReport(request);
long users = Int64.Parse(response.Rows[0].MetricValues[0].Value, CultureInfo.InvariantCulture);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment