3
votes

I'm trying to use the google sheets API to append new rows to an existing google sheet. Authentication already happens successfully and code is able to read the contents of the sheet. However, when I try to use service.spreadsheets().values().append(...), I get the following HttpError: "Invalid JSON payload received. Unknown name "": Root element must be a message."

Here is my code:

from json import dumps as jsdumps
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?version=v4')
service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)

spreadsheetId = '{...}'
rangeName = "Sheet1"
value_input_option = 'RAW'
insert_data_option = 'INSERT_ROWS'
value_range_body = {
    "range": rangeName,
    "majorDimension:": "ROWS",
    "values": list(rd.values()), # rd is just a dictionary with some stuff in it
}

So then when I try to send it:

request = service.spreadsheets().values().append(spreadsheetId=spreadsheetId, range=rangeName, valueInputOption=value_input_option, insertDataOption=insert_data_option, body=jsdumps(value_range_body))

After running request.execute(), I get the error listed above.

1
It seems your "rangeName" variable is incomplete. range should look like "Sheet1!A1:C3". Did you try that format? - noogui
[meta] I found this page as a copy of this page in Chinese: xbuba.com/questions/44706584 The question ID also matches the one on Stackoverflow. It's sad that they might not be able to access the original Stackoverflow , and this might be the only alternative to them. So much waste due to politics. - gregn3

1 Answers

1
votes

I was having a similar problem. This worked for me:

   spreadsheetId = 'foobar'
    range = 'Sheet1!A1'
    body = {
        'values': [data],
        "majorDimension:": "ROWS",

    }



    self.service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range,
                                                    valueInputOption='RAW',
                                                    insertDataOption='INSERT_ROWS',
                                                    body=body).execute()