create a google sheet file stored in my google drive and share it with python

Viewed 40

Hello I would like to know how is it possible to create a google sheet file stored in my google drive and share it to a specified email with python

1 Answers

you can easily create files and share them using the Drive API.

We will need to use 2 methods from 2 different APIs:

As a prerequisite you need to create a Google Cloud Project and add the Google Drive API and Google Docs API. Applications are identified by an OAuth 2.0 Client ID. Keep in mind that in order to maintain a reliable service for all users Google will limit how many API calls you can make in a day, minute or second. You can see the details of every quota in the project you created by following the steps in this Help Center article https://support.google.com/a/answer/6301355.

The code will prompt the user to sign in to the account where the application will create a file and then create the permission to the resulting file. After the user completes the login process a token will be created, a token will allow the code to run again without asking the user for consent again. Tokens may expire after different events, see a full list in this documentation https://developers.google.com/identity/protocols/oauth2#expiration.

Code sample:

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
 
# Scopes required to make both API calls -> https://developers.google.com/docs/api/reference/rest/v1/documents/create
SCOPES = ["https://www.googleapis.com/auth/drive"]  

DOCUMENT_NAME = "fileName"
SHARE_TO_USER = "user@domain.com"

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())

try:
    service = build('docs', 'v1', credentials=creds)

    # Create a new document with a determined name. The contents of the document can be set using additional API calls.
    newDocument = service.documents().create(body={'title':DOCUMENT_NAME}).execute()

    newFileID = newDocument.get('documentId')

    print('The fileId of the new document is: {}'.format(newFileID))

    service = build('drive', 'v3', credentials=creds)

    # Create the permission.

    parameters = {
        'role': 'reader',
        'type': 'user',
        'emailAddress': SHARE_TO_USER
    }

    newPermission = service.permissions().create(fileId=newFileID, body=parameters).execute()

    print('The new permissionId of the document is: {}'.format(newPermission.get('id')))
except HttpError as err:
    print(err)

Note: please be knowledgeable aware that Stack Overflow is best used when you don't simply ask for a code solution, I am kindly provising this sample as it takes little time to make and it works great to ilustrate the flow of data and the API calls. This is stated in this page https://stackoverflow.com/tour and I quote:

Don't ask about... Questions you haven't tried to find an answer for (show your work!)

Related