Analytics Reporting API V4 Client Library for .NET
Analytics Reporting API V4 Client Library for .NET
Calling the Google Analytics Reporting API from C# is not particularly difficult, however all of the necessary steps do not seem to be outlined very clearly in the Google Analytics API documentation. I will try to list them all out here. While YMMV, I believe these steps to be correct as of 7/20/2016.
You can start by creating a new C# project. We'll make a console application to test called GoogleAnalyticsApiConsole
. Once the project is created, we'll add a reference to the Google Analytics Reporting API V4 Client Library for .NET using the NuGet Package Manager Console (found under the Tools menu in Visual Studio 2015). Fire up the Console and issue the following command at the PM>
prompt:
PM> Install-Package Google.Apis.AnalyticsReporting.v4
Installing that package will download the client libraries needed to call the Google Analytics Reporting web services along with a number of other dependencies.
In order to call the web services, you'll need to set up OAuth 2.0 access for your application. The documentation for this setup can be found here, but I will summarize below:
-
Login to the Google Cloud Platform Console: https://console.cloud.google.com/. Be sure to login with an account that has access to the Google Analytics accounts you are trying to query with the reporting API.
-
Click the Google Cloud Platform menu and select API Manager.
-
On the left hand side, click Credentials and then create a new project called
Google Analytics API Console
. Give it some time to create the new project. -
After the project is created, click Credentials again if it is not already selected, and then click the OAuth Consent Screen link in the right panel. Set the Product name shown to users to
Google Analytics API Console
and then click Save. -
Click Credentials again, and then click Create Credentials, and choose OAuth Client ID. Select Other for Application type and then enter
Google Analytics API Console
as the Name and click Create. -
After the credential is created, you will be presented with a client ID and a client secret. You can close the dialog window.
-
Now, under Credentials you should see an entry under OAuth 2.0 client ids. Click the download icon to the far right of that entry to download the
client_secret.json
file (this file will have a much longer name). Add that file to your project at the root level once it has been downloaded and rename it toclient_secret.json
.
- Now that the OAuth 2.0 credential has been created, we need to enable it to call the Reporting API. Select Overview and make sure Google APIs is selected in the right panel. Type in
Reporting
in the search box and select Analytics Reporting API V4 from the list. On the next screen, click Enable. Once this API has been enabled, you should be able to see it under the Enabled APIs list in the right panel.
Now that we've created our project and created our OAuth 2.0 credential, it is time to call the Reporting API V4. The code listed below will use the Google API and the client_secret.json
file to create a Google.Apis.Auth.OAuth2.UserCredential
to query the Reporting API for all sessions between the given date range for a View. The code is adapted from the Java example here.
Before executing the code, be sure to set the Build Action on the client_secret.json
file to Content and the Copy to Output Directory setting to Copy if newer. There are also two variables that need to be properly set. First, in the GetCredential()
method, set the loginEmailAddress
value to the email address used to create the OAuth 2.0 credential. Then, in the Main
method, be sure to set the ViewId
in the reportRequest
variable to the view that you want to query using the Reporting API. To find the ViewId
, log in to Google Analytics and select the Admin tab. From there, select the view you want to query in the View dropdown on the far right and select View Settings. The View ID will be displayed under Basic Settings.
The first time the code is executed, it will bring up a web page asking if you want to allow the Google Analytics API Console
to have access to the API data. Select Allow to proceed. From then on that permission will be stored in the GoogleAnalyticsApiConsole
FileDataStore
. If that file is deleted, then permission will need to be granted again. That file can be found in the %APPDATA%\GoogleAnalyicsApiConsole
directory.
Please note that I believe this scenario will meet the needs of the OP. If this application were to be distributed to clients, then a different OAuth 2.0 scheme would most likely be necessary.
Here is the code:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Google.Apis.AnalyticsReporting.v4; using Google.Apis.AnalyticsReporting.v4.Data; using Google.Apis.Auth.OAuth2; using Google.Apis.Services; using Google.Apis.Util.Store; namespace GoogleAnalyticsApiConsole { class Program { static void Main(string[] args) { try { var credential = GetCredential().Result; using(var svc = new AnalyticsReportingService( new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Google Analytics API Console" })) { var dateRange = new DateRange { StartDate = "2016-05-01", EndDate = "2016-05-31" }; 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 = "<<your view id>>" }; var getReportsRequest = new GetReportsRequest { ReportRequests = new List<ReportRequest> { reportRequest } }; var batchRequest = svc.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()); } } static async Task<UserCredential> GetCredential() { using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { const string loginEmailAddress = "<<your account email address>>"; return await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { AnalyticsReportingService.Scope.Analytics }, loginEmailAddress, CancellationToken.None, new FileDataStore("GoogleAnalyticsApiConsole")); } } } }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2015-04-07 C#的运算符重载
2015-04-07 dotfuscator初步