I\'m trying to get some data from our google analytics instance and I\'d like to use the Analytics Reporting API V4 Client Library for .NET (https://developers.google.com/ap
Here are the steps updated for Sep 2019.
First, understand that there are two choices under OAuth: User credentials and Service Account credentials. User credentials are meant to be used when you do not know which Google Analytics account you will be connected to, hence the user grants your application permission. Service Account credentials are meant to be used, e.g. if you build your own dashboard for your company to display Google Analytics data.
Most of the time, if you need programmatic access to Analytics data, it is the second case.
The steps below should get you started for a simple C# example. Note that the Google web console part may vary slightly, but should be easy to find nevertheless.
xxx@xxx.iam.gserviceaccount.com
)The Google configuration is done. Now jump into Visual Studio.
using Google.Apis.AnalyticsReporting.v4.Data;
using System;
namespace ConsoleApplication {
class Program {
static void Main(string[] args) {
var credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromFile("serviceAccount.json")
.CreateScoped(new[] { Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService.Scope.AnalyticsReadonly });
using (var analytics = new Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService(new Google.Apis.Services.BaseClientService.Initializer {
HttpClientInitializer = credential
})) {
var request = analytics.Reports.BatchGet(new GetReportsRequest {
ReportRequests = new[] {
new ReportRequest{
DateRanges = new[] { new DateRange{ StartDate = "2019-01-01", EndDate = "2019-01-31" }},
Dimensions = new[] { new Dimension{ Name = "ga:date" }},
Metrics = new[] { new Metric{ Expression = "ga:sessions", Alias = "Sessions"}},
ViewId = "99999999"
}
}
});
var response = request.Execute();
foreach (var row in response.Reports[0].Data.Rows) {
Console.Write(string.Join(",", row.Dimensions) + ": ");
foreach (var metric in row.Metrics) Console.WriteLine(string.Join(",", metric.Values));
}
}
Console.WriteLine("Done");
Console.ReadKey(true);
}
}
}