Search code examples
python-3.xgoogle-sheetsgoogle-api-clientgoogle-api-python-client

AttributeError: 'str' object has no attribute 'request'


I'm able to successfully establish connection without any error, but when I try to read the data from sheet I'm running into AttributeError

import os
from googleapiclient import discovery
import pandas as pd

credential = 'reference/config.json'
api_name = 'sheets'
api_version = 'v4'
scope = ['https://www.googleapis.com/auth/spreadsheets']

service = discovery.build('sheets','v4',credentials=credential)

sheet_id = [sheet_id]
ranges = 'Sheet1!D5:J36'

sheet = service.spreadsheets()
request = sheet.values().get(spreadsheetId=sheet_id, range=ranges, majorDimension='ROWS')
response = request.execute()

AttributeError: 'str' object has no attribute 'request' is occuring at second last line (request = sheet.values().get(spreadsheetId=sheet_id, range=ranges, majorDimension='ROWS')

I followed the exact instructions provided at the documentation page https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get


Solution

  • previously I was not using authorization for my credentials to work, in the below piece of code I've added authorization piece followed by credentials for the code to work properly

    from __future__ import print_function
    import os.path
    from googleapiclient.discovery import build
    from google.oauth2 import service_account
    
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
    SERVICE_ACCOUNT_FILE = 'config.json'
    #config.json is your GCP Service Account Credential file which gets downloaded
    
    creds = None
    creds = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    
    # The ID and range of a sample spreadsheet.
    SAMPLE_SPREADSHEET_ID = '[SpreadsheetID]'
    SAMPLE_RANGE_NAME = '[SheetName]![Range]'
    
    service = build('sheets', 'v4', credentials=creds)
    
    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                    range=SAMPLE_RANGE_NAME).execute()
    #values = result.get('values', [])
    print(result)