2

I am using Google.Apis.AnalyticsReporting.v4 library for old google analytics views. How do I convert this code to GA4? I can't find a line about switching View Id to something else in code.

I have checked this post "How do I get view id in GA4", but my properties already exist and I don't see option to modify them after creation.

using (var svc = new AnalyticsReportingService(authInitializer.CreateInitializer()))
{
    var dateRange = new DateRange
    {
        StartDate = analyticsParams.From.ToString("yyyy-MM-dd"),
        EndDate = analyticsParams.To.ToString("yyyy-MM-dd")
    };
    var sessions = new Metric
    {
        Expression = "ga:sessions",
        Alias = "Sessions"
    };
    var date = new Dimension { Name = "ga:date" };

    var reportRequest = new ReportRequest
    {
        DateRanges = new List<DateRange> { dateRange },
        Dimensions = new List<Dimension> { date },
        Metrics = new List<Metric> { sessions },
        ViewId = analyticsParams.ViewId, // <------------------------- My view id
    };

    var getReportsRequest = new GetReportsRequest
    {
        ReportRequests = new List<ReportRequest> { reportRequest }
    };

    var batchRequest = svc.Reports.BatchGet(getReportsRequest);
    var response = batchRequest.Execute();

    var reports = response.Reports.First();

    return reports.Data.Rows.Select(x => new DataEntry()
    {
        Date = DateTime.ParseExact(x.Dimensions[0], "yyyyMMdd", CultureInfo.InvariantCulture),
        Value = int.Parse(x.Metrics[0].Values[0]),
    }).ToList();
}
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40

1 Answers1

0

You need to use the Google Analytics Data API V1 (currently in alpha) in order to access your GA4 properties. Here is a quick start sample for .NET which seems similar to what you are trying to do.

using Google.Analytics.Data.V1Alpha;
using System;

namespace AnalyticsSamples
{
    class QuickStart
    {
        static void SampleRunReport(string propertyId)
        {
            // Using a default constructor instructs the client to use the credentials
            // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
            AlphaAnalyticsDataClient client = AlphaAnalyticsDataClient.Create();

            // Initialize request argument(s)
            RunReportRequest request = new RunReportRequest
            {
                Entity = new Entity{ PropertyId = propertyId },
                Dimensions = { new Dimension{ Name="city"}, },
                Metrics = { new Metric{ Name="activeUsers"}, },
                DateRanges = { new DateRange{ StartDate="2020-03-31", EndDate="today"}, },
            };

            // Make the request
            RunReportResponse response = client.RunReport(request);

            Console.WriteLine("Report result:");
            foreach( Row row in response.Rows )
            {
                Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value);
            }
        }

        static int Main(string[] args)
        {
            if (args.Length == 0 || args.Length > 2)
            {
                Console.WriteLine("Arguments: <GA4 property ID>");
                Console.WriteLine("A GA4 property id parameter is required to make a query to the Google Analytics Data API.");
                return 1;
            }
            string propertyId = args[0];
            SampleRunReport(propertyId);
            return 0;
        }
    }
}
Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40
Ilya Kuleshov
  • 526
  • 2
  • 3
  • I have seen those APIs too but as for the measurement protocol they are in alpha and the documentation itself says to this is an early preview version of the API and is subject to change. While we will try to notify you of upcoming changes, you should expect to encounter breaking changes before the APIs are publicly released. My suggestion is not to use them yet if you want to get a sane result, using them on BigQuery instead. – Michele Pisani Nov 14 '20 at 09:37
  • I think I'll accept this answer. It looks closer to what I already have than BigQuery – Yehor Androsov Nov 15 '20 at 14:25