google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials

Question:

I am trying to follow https://developers.google.com/sheets/api/guides/values

I have the following python script:

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def get_values(spreadsheet_id, range_name):
    """
    Creates the batch_update the user has access to.
    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
        """
    creds, _ = google.auth.default()
    # pylint: disable=maybe-no-member
    try:
        service = build('sheets', 'v4', credentials=creds)

        result = service.spreadsheets().values().get(
            spreadsheetId=spreadsheet_id, range=range_name).execute()
        rows = result.get('values', [])
        print(f"{len(rows)} rows retrieved")
        return result
    except HttpError as error:
        print(f"An error occurred: {error}")
        return error


if __name__ == '__main__':
    # Pass: spreadsheet_id, and range_name
    get_values("id", "A1:C2")

I get the following error:

cchilders@cchilders-HP-ProBook-450-G3 ~/projects/update_stocks_interest_list $ python3 read_values.py 
Traceback (most recent call last):
  File "/home/cchilders/projects/update_stocks_interest_list/read_values.py", line 32, in <module>
    get_values("1N9hctlaS6gjRCVdpwgBx26dHr3tOFnE0125ybLuGvrk", "A1:C2")
  File "/home/cchilders/projects/update_stocks_interest_list/read_values.py", line 15, in get_values
    creds, _ = google.auth.default()
  File "/home/cchilders/.local/lib/python3.10/site-packages/google/auth/_default.py", line 616, in default
    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started
cchilders@cchilders-HP-ProBook-450-G3 ~/projects/update_stocks_interest_list $ ls
credentials.json  read_values.py

I logged into developers console and downloaded the Oauth2 file called client secret and renamed it to credentials.json as suggested online. The sheets api doc doesn’t explain how google.auth loads credentials. I tried creating a .env file in the project folder and setting GOOGLE_APPLICATION_CREDENTIALS to credentials.json, the file in the same folder. It got the same error.

How can I get this script to work with my credentials?

Asked By: codyc4321

||

Answers:

GOOGLE_APPLICATION_CREDENTIALS should typically point to a service account file path.

From Google’s docs on the topic, you’ll want to:

  1. Create a service account with the correct permissions for your service
  2. Download that service account as a JSON file.
  3. Point GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file, e.g. GOOGLE_APPLICATION_CREDENTIALS='/src/my-service-account.json'.

Specifics steps (credit Google documentation)

  1. Create the service account: gcloud iam service-accounts create NAME

  2. Add the permissions policy for the service account: gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=ROLE

  3. Create the service account JSON file: gcloud iam service-accounts keys create FILE_NAME.json --iam-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

  4. Export your environment variable in your current shell or a file that you source: export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Answered By: Jason R Stevens CFA
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.