0
votes

I'm trying to apply filter on my google sheet using python sheets API. I'm getting this error, and there are no any hints to debug this error. My code looks like this. I tried to print the requests body, which is exactly in the same format as that suggested on API documentation(https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#setbasicfilterrequest).

My code looks like this :

from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

import pandas as pd
import json 

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

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1ViILuxI3MD3vT7efWYDmlo5A67dIIDJbWXh6Pm9myPQ'
SAMPLE_RANGE_NAME = 'Sheet1!A2:I'

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    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(
                'credentials.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())

    service = build('sheets', 'v4', credentials=creds)

    _filter = {
        "range": {
            "sheetId": 0,
            "startRowIndex": 1,
            "startColumnIndex": 9,
            "endColumnIndex": 10
        },

        "criteria" : {
            9 : {
                "hiddenValues" : [
                    "Closed"
                ]
            }
        }
    }

    setBasicFilterRequest = {
        'setBasicFilter' : {
            'filter' : _filter
        }
    }

    body = { 
        'requests' : [setBasicFilterRequest],
        'includeSpreadsheetInResponse' : True,
        
    }

    # print(json.dumps(body, indent=4))
    resp = service.spreadsheets() \
   .batchUpdate(spreadsheetId="Sheet1", body=body).execute()

    print(resp)


if __name__ == '__main__':
    main()

I'm getting following error when I run this :

Traceback (most recent call last):
  File "poll_sheets.py", line 79, in <module>
    main()
  File "poll_sheets.py", line 72, in main
    resp = service.spreadsheets() \
  File "/Users/mike/Desktop/redash/myenv/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/mike/Desktop/redash/myenv/lib/python3.8/site-packages/googleapiclient/http.py", line 920, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://sheets.googleapis.com/v4/spreadsheets/Sheet1:batchUpdate?alt=json returned "Requested entity was not found.". Details: "Requested entity was not found.">
(myenv) (base) mike@Mikes-MacBook-Pro redash % 
1

1 Answers

2
votes

Modification points:

  • When I saw your script, it seems that SAMPLE_SPREADSHEET_ID is not used.
  • About resp = service.spreadsheets().batchUpdate(spreadsheetId="Sheet1", body=body).execute(), it seems that you use the sheet name as the Spreadsheet ID. I think that this is the reason of your issue.

When above points are reflected to your script, it becomes as follows.

Modified script:

resp = service.spreadsheets().batchUpdate(spreadsheetId="Sheet1", body=body).execute()
resp = service.spreadsheets().batchUpdate(spreadsheetId=SAMPLE_SPREADSHEET_ID, body=body).execute()

Note:

  • When you run above modified script and the same error occurs, please confirm the Spreadsheet ID again.

Reference: