1
votes

Overview

  • I am creating a folder and spreadsheets using API I can access all files inside that folder using google spreadsheet API
  • (problem) But then I upload the file from the front, Now this file can not be accessed via spreadsheet API, I have given full permission(owner) to the user.

So basically the problem is that I want to let other user drop spreadsheets in my shared drive and want to access these files via python API

error message "This operation is not supported for this document"

JSON RESPONSE

{ "error": { "code": 403, "message": "The request is missing a valid API key.", "status": "PERMISSION_DENIED" } }

Background:

I am using python to create folders and sheets, and I wanted to share the folder for other users to update the spreadsheet files so I gave permissions to other users, but when they dropped the files in the drive I can access the file metadata but not the contents of the spreadsheets

Relevant Code:

`SCOPES = ['https://www.googleapis.com/auth/drive.appdata','https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']

sheet_service = build('sheets', 'v4', credentials=get_Service())
drive_service = build('drive', 'v3',credentials=get_Service()) 

 def get_values(self,SAMPLE_SPREADSHEET_ID, SAMPLE_RANGE_NAME):
        sheet = sheet_service.spreadsheets()
        result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                    range=SAMPLE_RANGE_NAME).execute()`


Expected help > bypass these permission restrictions

I have noticed something when I drop the file the sheet id is different from when I create it with API or from google drive

1
OK the Problem is Resolved Thanks, how -- the question was very hard to understand the solution is simple the reason I was failing to access these files is because of file types == xls, i couldn't find a way to change type via API which is exactly i was not supposed to do, I did it via front end of drive settings and convert to google sheet formatMuhammad Yusuf
as i mentioned in my anwser if you upload the file to Google drive again this time request that it be converted it will the be a Google sheet that you can use the API onDaImTo

1 Answers

1
votes
{ "error": { "code": 403, "message": "The request is missing a valid API key.", "status": "PERMISSION_DENIED" } }

Means that you are not sending any authorization with your request. Your request needs to be authorized before you can do anything. Notice how the credentials have been added to the service variable in the code below.

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

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

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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.pickle', 'wb') as token:
            pickle.dump(creds, token)

    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', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print('%s, %s' % (row[0], row[4]))

if __name__ == '__main__':
    main()

Code ripped from Python quickstart

Also note that you cant create a folder in Google drive with the Sheets api you will need to use the Google drive api to create files. Sheets just lets you edit them.

converting files

When you upload the files to Google drive you need to convert them to sheet at that time Import doc types

file_metadata = {
    'name': 'My Report',
    'mimeType': 'application/vnd.google-apps.spreadsheet'
}
media = MediaFileUpload('files/report.csv',
                        mimetype='text/csv',
                        resumable=True)
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')