Python 向GoogleAnalyticisAPI发出请求时,需要登录

Python 向GoogleAnalyticisAPI发出请求时,需要登录,python,google-analytics,google-oauth,google-analytics-api,Python,Google Analytics,Google Oauth,Google Analytics Api,我从谷歌分析API v3获取数据 https://www.googleapis.com/analytics/v3/data/ga?ids=ga:181335694&metrics=ga:sessions&start-date=7daysAgo&end-date=today 一旦我运行浏览器就会抛出一个错误 { "error":{ "errors":[ { "domain":"global",

我从谷歌分析API v3获取数据

https://www.googleapis.com/analytics/v3/data/ga?ids=ga:181335694&metrics=ga:sessions&start-date=7daysAgo&end-date=today
一旦我运行浏览器就会抛出一个错误

{
   "error":{
      "errors":[
         {
            "domain":"global",
            "reason":"required",
            "message":"Login Required",
            "locationType":"header",
            "location":"Authorization"
         }
      ],
      "code":401,
      "message":"Login Required"
   }
}
如何解决此错误


一旦我运行python代码,我就会得到Google Analytics api,但我在浏览器中运行时会抛出错误,因为需要登录才能解决它。

当我们谈论Google api时,有两种类型的数据

不属于任何人和每个人都可以查看的公共数据 用户拥有的私有数据,您必须具有访问该数据的权限

“需要登录”

这意味着您必须通过身份验证才能访问您试图访问的数据。您需要该数据所有者的权限。你不能只是拿着那个get字符串在浏览器中启动它,你需要一个访问令牌才能做到这一点。您可以从身份验证流获取访问令牌

既然您提到了python,那么您应该遵循下面的步骤,这将向您展示如何设置项目和验证脚本,以便能够访问所需的数据

import argparse

from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools


def get_service(api_name, api_version, scope, client_secrets_path):
  """Get a service that communicates to a Google API.

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      client_secrets_path, scope=scope,
      message=tools.message_if_missing(client_secrets_path))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(api_name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service


def get_first_profile_id(service):
  # Use the Analytics service object to get the first profile id.

  # Get a list of all Google Analytics accounts for the authorized user.
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    # Get the first Google Analytics account.
    account = accounts.get('items')[0].get('id')

    # Get a list of all the properties for the first account.
    properties = service.management().webproperties().list(
        accountId=account).execute()

    if properties.get('items'):
      # Get the first property id.
      property = properties.get('items')[0].get('id')

      # Get a list of all views (profiles) for the first property.
      profiles = service.management().profiles().list(
          accountId=account,
          webPropertyId=property).execute()

      if profiles.get('items'):
        # return the first view (profile) id.
        return profiles.get('items')[0].get('id')

  return None


def get_results(service, profile_id):
  # Use the Analytics Service Object to query the Core Reporting API
  # for the number of sessions in the past seven days.
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='7daysAgo',
      end_date='today',
      metrics='ga:sessions').execute()


def print_results(results):
  # Print data nicely for the user.
  if results:
    print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
    print 'Total Sessions: %s' % results.get('rows')[0][0]

  else:
    print 'No results found'


def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.readonly']

  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, 'client_secrets.json')
  profile = get_first_profile_id(service)
  print_results(get_results(service, profile))


if __name__ == '__main__':
  main()

我怀疑如何设置json文件路径。get_service('analytics','v3',scope,'client_secrets.json')SystemExit:客户端机密无效:客户端类型“web”中缺少属性“redirect_URI”。警告:请配置OAuth 2.0确保下载了corect client_secrets.json文件,并按照有关如何创建该文件的教程进行操作。确保其与正在运行的脚本位于同一文件夹中