Created
September 17, 2016 16:19
-
-
Save markwemekamp/d309ed9a971cae5695cc5e545de16800 to your computer and use it in GitHub Desktop.
Read data from Google analytics using Google Analytics Reporting v4 and a Service account
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using Google.Apis.AnalyticsReporting.v4; | |
using Google.Apis.AnalyticsReporting.v4.Data; | |
using Google.Apis.Auth.OAuth2; | |
using Google.Apis.Services; | |
namespace Google_api | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
try | |
{ | |
var filepath = ""; // path to the json file for the Service account | |
var viewid = ""; // id of the view you want to read from | |
GoogleCredential credentials; | |
using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read)) | |
{ | |
string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly }; | |
var googleCredential = GoogleCredential.FromStream(stream); | |
credentials = googleCredential.CreateScoped(scopes); | |
} | |
var reportingService = new AnalyticsReportingService( | |
new BaseClientService.Initializer | |
{ | |
HttpClientInitializer = credentials | |
}); | |
var dateRange = new DateRange | |
{ | |
StartDate = "2016-07-01", | |
EndDate = "2016-07-31" | |
}; | |
var sessions = new Metric | |
{ | |
Expression = "ga:pageviews", | |
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 = viewid | |
}; | |
var getReportsRequest = new GetReportsRequest | |
{ | |
ReportRequests = new List<ReportRequest> { reportRequest } | |
}; | |
var batchRequest = reportingService.Reports.BatchGet(getReportsRequest); | |
var response = batchRequest.Execute(); | |
foreach (var x in response.Reports.First().Data.Rows) | |
{ | |
Console.WriteLine(string.Join(", ", x.Dimensions) + " " + string.Join(", ", x.Metrics.First().Values)); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.ToString()); | |
} | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code is broken.
I can get it to kind of connect I guess because the Console.WriteLine is working.
But it keeps loading. So my project is getting stuck when retrieving analytics data.
Please do you know what is wrong in the code?