pythongoogle-drive-apigoogle-sheets-apigoogle-authenticationgoogle-console-developer

How to create Google Sheets using Service Account Credential in Python?


I created Service Account Credentials here and got json key service.json.

Then I tried:

from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
credentials = service_account.Credentials.from_service_account_file(
        'service.json', scopes=SCOPES)

drive = build('drive', 'v3', credentials=credentials)
file_metadata = {
    'name': 'sampleName',
    'parents': ['#### folderId ###'],
    'mimeType': 'application/vnd.google-apps.spreadsheet',
}
res = drive.files().create(body=file_metadata).execute()
print(res)

With an error:

<HttpError 403 when requesting https://www.googleapis.com/drive/v3/files?alt=json returned "Insufficient Permission: Request had insufficient authentication scopes.">

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

I found that without an Auth header, I am anonymous, and the quota for anonymous use is zero. How can I set header or the reason for this error is something else?

All I want is to create a spreadsheet with python in my gdrive folder from any computer without a need to click somewhere to grant access.


Solution

  • If my understanding is correct, how about this answer?

    Modification point:

    Modified script:

    When your script is modified, please modify it as follows.

    from googleapiclient.discovery import build  # Added
    from google.oauth2 import service_account
    
    SCOPES = ['https://www.googleapis.com/auth/drive']  # Modified
    credentials = service_account.Credentials.from_service_account_file('service.json', scopes=SCOPES)
    
    drive = build('drive', 'v3', credentials=credentials)
    file_metadata = {
        'name': 'sampleName',
        'parents': ['#### folderId ###'],
        'mimeType': 'application/vnd.google-apps.spreadsheet',
    }
    res = drive.files().create(body=file_metadata).execute()
    print(res)
    

    Note:

    References: