【问题标题】:Difference in totalItems and actual items in google analytics api谷歌分析 api 中的 totalItems 和实际项目的差异
【发布时间】:2014-09-19 22:02:38
【问题描述】:

我正在尝试获取个人资料列表https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/profiles/list

以下是网页版的示例:

Request
GET https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles?key={YOUR_API_KEY}
Authorization:  Bearer
X-JavaScript-User-Agent:  Google APIs Explorer
Response
200 OK

- Hide headers -

Cache-Control:  private, max-age=0, must-revalidate, no-transform
Content-Encoding:  gzip
Content-Type:  application/json; charset=UTF-8
Date:  Tue, 09 Sep 2014 16:20:18 GMT
Etag:  "oq4YecK1DDgQfhLS-HzmxjZUB9I/ooSCrThtdvH0a3h5ysvIA31TDu0"
Expires:  Tue, 09 Sep 2014 16:20:18 GMT
Server:  GSE
Transfer-Encoding:  Identity

{
 "kind": "analytics#profiles",
 "username": "admin@domain.com",
 "totalResults": 38,
 "startIndex": 1,
 "itemsPerPage": 1000,
 "items": [
  ...
 ]
}

这是我使用 https://github.com/google/google-api-ruby-client/ gem 的示例 ruby​​ 代码。

  def self.ga_client
    client = Google::APIClient.new(
      application_name: configatron.google_analytics.application_name,
      application_version: configatron.google_analytics.application_version
    )

    key_file = File.join(configatron.google_analytics.pk12_file_path)
    key = Google::APIClient::PKCS12.load_key(key_file, 'notasecret')

    service_account = Google::APIClient::JWTAsserter.new(
      configatron.google_analytics.service_email,
      configatron.google_analytics.scope,
      key
    )

    client.authorization = service_account.authorize

    client
  end


        client = self.ga_client
        analytics = client.discovered_api('analytics', configatron.google_analytics.version)

        result = client.execute(
          api_method: analytics.management.profiles.list,
          parameters: {
            accountId: "~all",
            webPropertyId: "~all"
          }
        )
    Response
    #<Google::APIClient::Result:0x00000108c71a10 @request=#<Google::APIClient::Request:0x00000108cc3f90 @parameters={"accountId"=>"~all", "webPropertyId"=>"~all"}, @headers={"User-Agent"=>"DLM/1.0 google-api-ruby-client/0.7.1 Mac OS X/10.9.3\n (gzip)", "Accept-Encoding"=>"gzip", "Content-Type"=>""}, @api_method=#<Google::APIClient::Method:0x8474c6b8 ID:analytics.management.profiles.list>, @authenticated=nil, @authorization=#<Signet::OAuth2::Client:0x000001013435a8 @token_credential_uri=#<Addressable::URI:0x809a19e4 URI:https://accounts.google.com/o/oauth2/token>, @expiry=60, @extension_parameters={}, @additional_parameters={}, @scope=["https://www.googleapis.com/auth/analytics.readonly", "https://www.googleapis.com/auth/prediction"], @issuer="filtered@developer.gserviceaccount.com", @principal=nil, @audience="https://accounts.google.com/o/oauth2/token", @signing_key=#<OpenSSL::PKey::RSA:0x00000101341000>, @grant_type=nil, @refresh_token=nil, @code=nil, @issued_at=2014-09-09 20:19:07 +0400, @expires_in=3600, @access_token="ya29.ewBSHe0Wh5oGeKoe8aJtdpzVb-Nhr9SF0O39mdE1HgF3zTKs-8wBHL5M">, @body="">, @response=#<Faraday::Response:0x00000108c798c8 @on_complete_callbacks=[], @env=#<Faraday::Env @method=:get @body="{\"kind\":\"analytics#profiles\",\"username\":\"filtered@developer.gserviceaccount.com\",\"totalResults\":25,\"startIndex\":1,\"itemsPerPage\":1000,\"items\":...

从控制台只有 25 条记录,为什么会这样?我尝试使用 max-items 选项,但没有运气,有什么提示吗?

【问题讨论】:

  • 您是否查看过代码结果中缺少哪些视图?我的第一个想法是您正在请求两个不同的用户帐户,我知道这在过去发生在我身上......

标签: ruby-on-rails ruby google-analytics google-analytics-api google-api-client


【解决方案1】:

Google API 为您提供 options 参数

  • max-results:代表itemsPerPage。默认值为1000
  • start-index:代表页码。默认值为 1

因此,我认为更改 max-items(max-results) 的值不会有帮助,因为您只有 35 条记录。使用谷歌控制台,我们使用不同的帐户(xyz@gmail.com)和我们使用的 API(XXX@developer.gserviceaccount.com)

我使用谷歌客户端尝试了上述选项,它显示了正确的结果。

我是怎么做到的?

  1. 我共有 13 个 GA 帐户(xyz@gmail.com)。
  2. 授予 11 个帐户分析对 XXX@developer.gserviceaccount.com 的只读权限
  3. 尝试使用 GA 客户端库向我显示 totalResults=11 及其项目详细信息。
  4. 使用Views (Profiles): list play 使用 OAuth 2.0 权限检查了我的个人资料结果。它显示了 totalResults=13 条记录
  5. 通过检查服务名称来交叉验证 google 客户端 API 记录。它向我显示了我为开发者电子邮件帐户 XXX@developer.gserviceaccount.com 授予访问权限的相同服务。

我确定您已按照以下步骤操作。请再次交叉验证。

  1. 转到Google API Console 并创建一个新项目
  2. 在 API 访问选项卡中,单击创建 OAuth2.0 客户端 ID

    • 选择服务帐户选项并按创建客户端 ID
    • 下载私钥
    • 复制服务帐户电子邮件地址,即XXXX@@developer.gserviceaccount.com
    • 访问您的 GA Admin 并将此电子邮件作为用户添加到您的属性中
    • 这是必须的;否则你会得到一些神秘的错误。
  3. 使用 Google Enable Api 向我的项目授予 Google Analytics 权限

  4. 通过 Gem 获取最新的 Google Ruby Client API

    source "https://rubygems.org"
    gem 'google-api-client', '>= 0.6'
    
  5. 您的 API 访问代码。我的如下

    require 'google/api_client'
    require 'json'
    
    API_VERSION = 'v3'
    CACHED_API_FILE = "analytics-#{API_VERSION}.cache"
    
    # Update these to match your own apps credentials
    service_account_email = 'XYZ@developer.gserviceaccount.com'
    key_file = 'client.p12' # File containing your private key
    key_secret = 'notasecret' # Password to unlock private key
    
    
    client = Google::APIClient.new(
      :application_name => 'Plus Test', #Application name
      :application_version => '1')
    
    # Load our credentials for the service account
    key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
    client.authorization = Signet::OAuth2::Client.new(
      :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
      :audience => 'https://accounts.google.com/o/oauth2/token',
      :scope => ['https://www.googleapis.com/auth/analytics','https://www.googleapis.com/auth/analytics.edit','https://www.googleapis.com/auth/analytics.readonly'],
      :issuer => service_account_email,
      :signing_key => key)
    
    
    # Request a token for our service account
    client.authorization.fetch_access_token!
    
    analytics = nil
    # Load cached discovered API, if it exists. This prevents retrieving the
    # discovery document on every run, saving a round-trip to the discovery service.
    if File.exists? CACHED_API_FILE
      File.open(CACHED_API_FILE) do |file|
        analytics = Marshal.load(file)
      end
    else
      analytics = client.discovered_api('analytics', API_VERSION)
      File.open(CACHED_API_FILE, 'w') do |file|
        Marshal.dump(analytics, file)
      end
    end
    
    
    result = client.execute(:api_method => analytics.management.profiles.list, :parameters => {
      'alt' => "json",
      'accountId' => "~all",
      'webPropertyId' => "~all",
      'fields' => 'items(id,name,permissions,websiteUrl),itemsPerPage,startIndex,totalResults,username',
      'max-results' => 1, #used to get number of records. Default value is 1000
      'start-index' => 1 #This is page number. Default value is 1
    })
    
    #Response result
    result = JSON.parse(result.data.to_json)
    print result
    
  6. 使用bundle exec ruby test.rb执行代码

  7. 以上代码打印关联账户的json。

结论:您可能错过了为某些属性/帐户授予开发者电子邮件的 GA 权限。请与 XXX@developer.gserviceaccount.com

交叉验证实际 GA 帐户 (xyz@gmail.com) 个人资料列表

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    相关资源
    最近更新 更多