Google Sheets API “update” method Http Error 400

余生长醉 提交于 2019-11-30 15:08:13

I also started with the API example. Above information about enabling both APIs, for Drive and Sheets, helped me solving the access error.

Then I found that the .get(...).execute() returns an object, which is the type that is needed as input in the .update().execute(), it looks like:

{u'range': u'Sheet1!A1:B2', u'values': [[u'cella1', u'cellb1'],
[u'cella2', u'cellb2']], u'majorDimension': u'ROWS'}

After having made a fit between ranges, and also adding the argument valueInputOption='RAW' to the .update(), I successfully wrote to the Google sheet with this code snippet:

myBody = {u'range': u'Sheet1!A1:B2', u'values': [[u'Zellea1', u'Zelleb1'], [u'Zellea2', u'Zelleb2']], u'majorDimension': u'ROWS'}
rangeOutput = 'Sheet1!A1:B2'
res = spreadsheet.values().update( spreadsheetId=spreadsheetId, range=rangeOutput, valueInputOption='RAW', body=myBody ).execute()

I setup myself to have a google dev account and encountered several setbacks, but I was able to manage.

I'm pretty sure the 401 is due to the incorrect JSON file provided to authenticate (specially if you have several projects and have downloaded several JSON files)

I also encountered a 403 indicating the API for my google drive was not enabled:

make sure that you have both api's enabled (for the drive and the spreadhseets)

Most of the time, when executing my code, the console returned a pretty clear Error and pointed towards the right direction:

raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: https://sheets.googleapis.com/v4/spreadsheets/DocumentID/values/Class%20Data%21A2%3AE?alt=json returned "Google Sheets API has not been used in project pytestapp before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=pytestapp then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.">

Process finished with exit code 1

I figured out that the body arg included in update(), although shown in the documentation as json, actually needs to be a regular python dictionary. I was sending a body of text in json, and what the google api client was looking for was an actual python dict object I guess.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!