0

I'm trying to follow the Google Sheet API from its documentation here: https://developers.google.com/sheets/api/guides/values

I'm trying to run the snippets of the codes mentioned there, for example, Python code on Reading a single range

Here is an example of a snippet of code that I ran, sheets_get_values.py

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):
    creds, _ = google.auth.default()
    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__':
    get_values("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", "A1:C2")

python3 sheets_get_values.py

But I got this message:

An error occurred: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k/values/A1%3AC2?alt=json returned "Request had insufficient authentication scopes.". Details: "[{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'ACCESS_TOKEN_SCOPE_INSUFFICIENT', 'domain': 'googleapis.com', 'metadata': {'method': 'google.apps.sheets.v4.SpreadsheetsService.GetValues', 'service': 'sheets.googleapis.com'}}]">

I have tried to set the GOOGLE_APPLICATION_CREDENTIALS environment:

export GOOGLE_APPLICATION_CREDENTIALS='/home/myUser/.config/gcloud/application_default_credentials.json'

I also already enable application default credentials:

gcloud auth application-default login

gcloud config set project project_name

I also try to solve this by following a few instructions related to Request had insufficient authentication scopes by Googling, for example this one

I try to modify the default snippet of code by Google documentation be like this:

SCOPES = [
    'https://www.googleapis.com/auth/drive',
    'https://www.googleapis.com/auth/drive.file',
    'https://www.googleapis.com/auth/spreadsheets',
]

def append_values(spreadsheet_id, range_name, value_input_option,
                  _values):
    creds, _ = google.auth.default(scopes=SCOPES)
    ...
    ...

But the error still appear when I ran the snippet of the code.

So, what should I do to solve this error?

Tri
  • 2,722
  • 5
  • 36
  • 65
  • do you use v2 auth? 403 means forbiden access.... you shoul dbe getting a token request, then validate etc. just making sure it is not the issue. google is full of old tutorials and had similar issue before... – Je Je Dec 29 '22 at 19:51

2 Answers2

2

Instead of:

gcloud auth application-default login

Try passing in additional scopes:

gcloud auth application-default login --scopes=https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/spreadsheets

You may also need to unset GOOGLE_APPLICATION_CREDENTIALS before application-default login works.

Joshmaker
  • 4,068
  • 3
  • 27
  • 29
1

The problem is in the Sheet you are trying to get data from. It is unavailable, you can try to navigate to it.

Replace the sheet id (1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k) with some that is available to your Google account. You can try this one - 1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms (this is the test sheet).

elebur
  • 465
  • 1
  • 5
  • Actually I already tried the real sheet id like this `17rkVniBQLZOrOy6uH-BloWK6nXqfd7IWap64dCu07N8`, but still getting the same error. – Tri Dec 18 '22 at 13:23
  • But the sheet [`17rkVniBQLZOrOy6uH-BloWK6nXqfd7IWap64dCu07N8`](https://docs.google.com/spreadsheets/d/17rkVniBQLZOrOy6uH-BloWK6nXqfd7IWap64dCu07N8) isn't available either, at least for me. Is it your sheet? Perhaps you created it in one account and tried reading from another one that doesn't have access rights. – elebur Dec 18 '22 at 13:59
  • HI @elebur, yes, that is my sheet, and I have access to it. And in the other hand actually I also already tried your mentioned id `1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms`, but the result is still the same. – Tri Dec 19 '22 at 00:24
  • Hello, @Tri. I am not sure what the problem is, but I assume it is related to the created Google project. Did you enable Sheet and Drive API? How did you get the credentials? – elebur Dec 19 '22 at 14:28
  • Hi @elebur, yes I have enabled the Sheet and Drive API. I created credentials from the **APIs & Services** menu, then on the **Credentials** tab, click on the **CREATE CREDENTIALS** button, then click on the **OAuth client ID**, and on the **Application type** I selected the **Desktop app**, then I download its JSON file, then set the `GOOGLE_APPLICATION_CREDENTIALS` to the JSON file path. Did I do the wrong step? – Tri Dec 19 '22 at 15:19
  • Seems everything is ok with credentials, as for me. Try this code https://pastebin.com/8DGzs7d4, it differs a little from yours. – elebur Dec 19 '22 at 16:32
  • When I run the code, it open my browser and require me to authenticate first, after that I got this message on the browser: `The authentication flow has completed. You may close this window.` But I got this error on my console where I ran the python file: https://pastebin.com/jWM6XZYV – Tri Dec 21 '22 at 10:42
  • @Tri, I've been thinking about your problem but don't know what else it might be. I still assume it is related to the google project. Try creating a new one (perhaps with a new account). What is the [publishing status](https://console.cloud.google.com/apis/credentials/consent) of the project? Is it "Testing" or "In production"? If it is "testing" try setting "In production". – elebur Dec 24 '22 at 11:11