Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google API google.auth.exceptions.RefreshError: 'invalid_scope: Bad Request'

I am writing a small Python program that reads from Google sheets. Everything was right with the code up to yesterday. However, when I tried to run it today it didn't work.

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

# The spreadsheet ID
SPREADSHEET_ID = 'My spreadsheet ID'

def main():

    # Sets the range
    RANGE = 'My range'

    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'creds.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

When I try to run it, the following Error shows up:

File "path/to/file/file.py", line 50, in main
    creds.refresh(Request())
File "/home/User/.local/lib/python3.9/site-packages/google/oauth2/_client.py", line 60, in _handle_error_response
    raise exceptions.RefreshError(error_details, response_data)
google.auth.exceptions.RefreshError: ('invalid_scope: Bad Request', {'error': 'invalid_scope', 'error_description': 'Bad Request'})
like image 915
Victor Cruz Avatar asked Jul 14 '26 23:07

Victor Cruz


2 Answers

I don't know what happened either but for a quick solution, I deleted the token.json file and ran the script again

like image 56
Phicks Avatar answered Jul 17 '26 15:07

Phicks


The error is complaining about scope not being correct. You should make sure whether the scope you have declared in SCOPES variable is same as the value of scopes available in token.json.

If you want to change your scope, you will have to generate a new token.json file by deleting the old one first.

like image 30
Saurabh Sengar Avatar answered Jul 17 '26 17:07

Saurabh Sengar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!