1

I have been trying really hard to do my code working just by reading examples, but i can't find an example about the correct way of writting in a sheet using the API.

Here's the part of my code that it isn't working:

def comprar(producto,cantidad):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                'version=v4')
service = discovery.build('sheets', 'v4', http=http,
                          discoveryServiceUrl=discoveryUrl)

spreadsheetId = '1oN1WkdXSYIlsgjFKZX1YolwajNflqAgE20w8vcRaY8Y'
row = searchInCol("A",producto)
target = "Inventario!"+"J"+str(row)
values = [
    [
        # Cell values to be inputed...
        int(cantidad)
    ],
# Additional rows ...
]
body = {"values":values}
print("Entra")

#THIS ISN'T WOKRING
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheetId, range=target,
valueInputOption="USER_ENTERED", body=body).execute()
print("entra")

The function that is not working is the comprar one, the console says: "Request had insufficient authentication scopes". I can't even understand what it means. By the way here you have the function get_credentials():

def get_credentials():
"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.

Returns:
    Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
                               'sheets.googleapis.com-python-quickstart.json')

store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    flow.user_agent = APPLICATION_NAME
    if flags:
        credentials = tools.run_flow(flow, store, flags)
    else: # Needed only for compatibility with Python 2.6
        credentials = tools.run(flow, store)
    print('Storing credentials to ' + credential_path)
return credentials

And here I have all the modules imported:

from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import time

If anyone could explain me a little bit of what's wrong and an example of a working code for writing in a google sheet using python and the API, it would be really helpful. And also, if you need any more information about the code, please tell me. (I'm just a noob student.)

Edit: I've changed this:

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'

To this:

SCOPES = 'https://www.googleapis.com/auth/spreadsheets'

But it keeps throwing the following error:

Traceback (most recent call last):
  File "quickstart.py", line 210, in <module>
  comprar(pro,cnt)
  File "quickstart.py", line 196, in comprar
valueInputOption="USER_ENTERED", body=body).execute()
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 838, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/1oN1WkdXSYIlsgjFKZX1YolwajNflqAgE20w8vcRaY8Y/values/Inventario%21J1?alt=json&valueInputOption=USER_ENTERED returned "Request had insufficient authentication scopes.">

Thanks!

Kevin Zeledon
  • 23
  • 1
  • 5

1 Answers1

2

Well, make sure that you enable all the API that you used here especially the Sheets API in your Developers Console.

The error "Request had insufficient authentication scopes" that you receive is an error in the OAuth 2.0 token provided in the request that specify the scopes that you are using are insufficient for accessing the requested data.

So make sure you follow the steps here on this documentation on how to Authorize your request with OAuth.

For more information, you can check this related SO question.

Community
  • 1
  • 1
KENdi
  • 7,576
  • 2
  • 16
  • 31