pythongoogle-analytics-api

google.auth.exceptions.DefaultCredentialsError [Python]


import json
import csv
import google.analytics.data


# Load the JSON key file
with open('key.json', 'r') as f:
    service_account_info = json.load(f)

# Create a service account object
service_account = service_account_info['client_email']

# Create a Google Analytics Reporting API client
client = google.analytics.data.BetaAnalyticsDataClient()


# Set the view ID
view_id = '74466483'

# Set the date range
start_date = '2023-01-01'
end_date = '2023-05-01'

# Define the metrics and dimensions
metrics = ['ga:sessions', 'ga:bounce_rate', 'ga:average_time_on_page', 'ga:entrances', 'ga:pageviews', 'ga:unique_pageviews']
dimensions = ['ga:source', 'ga:page']

# Run the report
report = client.run_report(
    view_id,
    start_date,
    end_date,
    metrics,
    dimensions
)

# Write the report to a CSV file
with open('report.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(report.header)
    for row in report.rows:
        writer.writerow(row)

ERROR:


$ python CompanyName.py 
Traceback (most recent call last):
  File "C:\Users\Daniel Kamen\Desktop\CompanyNameCode\CompanyName.py", line 14, in <module>
    client = google.analytics.data.BetaAnalyticsDataClient()
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MYNAME\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\google\analytics\data_v1beta\services\beta_analytics_data\client.py", line 426, in __init__
    self._transport = Transport(
                      ^^^^^^^^^^
  File "C:\Users\MYNAME\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\google\analytics\data_v1beta\services\beta_analytics_data\transports\grpc.py", line 148, in __init__
    super().__init__(
  File "C:\Users\MYNAME\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\google\analytics\data_v1beta\services\beta_analytics_data\transports\base.py", line 100, in __init__
    credentials, _ = google.auth.default(
                     ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MYNAME\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\google\auth\_default.py", line 648, in default
    raise exceptions.DefaultCredentialsError(_CLOUD_SDK_MISSING_CREDENTIALS)
google.auth.exceptions.DefaultCredentialsError: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information.

I was given administrator access to my company's google analytics account, so I'm really lost at whats needed to run this. The goal is to export the company data into a csv file to help transition our old data into GA4

I really am lost so I'm not sure what to try.


Solution

  • That's because, as documentation explains, the method BetaAnalyticsDataClient() does accept an optional options object, that has credentials inside.

    Whether it isn't provided, it will search for default ones (that in your case aren't instantiated).

    To specify them, simply:

    client = google.analytics.data.BetaAnalyticsDataClient(options={"credentials":{"client_email": service_account, "private_key": "YOUR_KEY"}})
    

    Or, for a more readable alternative, create a dict outside and call it.

    credentials_dict = {
        "options": {
            "client_email": service_account,
            "private_key": "YOUR_KEY"
        }
    }
    client = google.analytics.data.BetaAnalyticsDataClient(options=credentials_dict)
    

    Either, if you have gcloud SDK in your computer, you can visit the suggested link in the error message and setup a default credential!

    Hope it actually fixes your problem. I do not have Google Analytics credentials so I cannot test it.