Google 分析报告 API 抛出 401

Google Analytics Reporting API throwing 401s

我正在尝试从 google 分析报告中获取一个非常简单的数据集,但尚未对其进行身份验证。我真的迷路了。我一直在使用 APIs 资源管理器来测试我正在尝试做的事情,但似乎无法进行简单的批量获取。我已经删除了关键字段 (obv)

这基本上就是我要发回的内容:服务 > Google 分析报告 API v4 > analyticsreporting.reports.batchGet

注意:我不是想做 OAuth2,只是用服务器 API 密钥触发这些东西。

POST https://analyticsreporting.googleapis.com/v4/reports:batchGet?fields=reports&key=XXX
{
 "reportRequests": [
  {
   "dateRanges": [
{
 "startDate": "2014-06-23",
 "endDate": "2016-06-23"
}
],
"orderBys": [
{
 "fieldName": "ga:pageviews",
 "sortOrder": "DESCENDING"
}
],
"dimensions": [
 {
 "name": "ua:page"
 }
]
},
{
  "viewId": "7070072"
}
]
}

这是返回的内容:

{
  "error": {
  "code": 401,
  "message": "The request does not have valid authentication credentials.",
  "status": "UNAUTHENTICATED"
 }
}

API 密钥用于未经验证的 API,例如 Google Analytics Metadata API. The Analytics Reporting API V4 requires a valid OAuth token. Think about it this way, would you want just anyone with an API key to access your GA data? The API needs to verify that the user has the authority to access the data. Please read through the various OAuth Scenarios 并找到与您的用例匹配的密钥。

听起来您想使用 service account. The issue is not with your analytics code but how you are authenticating. In order to make the request you need to have a valid OAuth token. Since you specifically listed that you are interested in .NET you should look at the Google APIs .NET client library documentation 进行身份验证。请记住,您需要将服务帐户电子邮件添加到您希望访问的 Google 分析视图。