Automate with Google API's

Outline

Authenticating with Google services opens a world of possibilities for automation - auto-populating complex Google Docs, inserting data to Google Sheets, moving files around in Google Drive, and much more! This article will introduce a small Python class to ease working with Google API's and hopefully help you feel more comfortable integrating with the Google ecosystem.

Note: We will be focusing on Google Service accounts which allow connecting with Google API's without any user interaction.

Install the Google packages for Python

To begin, open your favorite terminal and install the Google Python API Client and supporting packages.

# use pip3 for Linux
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Create the Google Service class

Open your favorite editor and create a new folder to house this project. Once that is completed, you will want to create a new file named google_service_account.py. Paste in that file the following code. This Python class is not necessary, but will greatly ease access to the Google API :)

import os
from apiclient import discovery
from google.oauth2 import service_account

class GoogleService:
    """
    Build a Google Service Connector. Call .getService() to access the API
    """
    def __init__(self, scopes, api, version, token_file='token.json', token_path=os.getcwd()):
        self.scopes     = scopes
        self.api        = api
        self.version    = version
        self.token_file = token_file
        self.toke_path  = token_path
        self.service    = None

    def getService(self):
        """
            Get the service instance. Will connect if not already existing.
        """
        if self.service:
            return self.service

        secret_file = os.path.join(self.token_path, self.token_file)
        credentials = service_account.Credentials.from_service_account_file(secret_file, scopes=self.scopes)
        self.service = discovery.build(self.service, self.version, credentials=credentials)

        return self.service

Access the API

Setup

First, create a new Python file, main.py, in the same directory as the google_service_account.py file. Open your new file and import the GoogleService class:

from google_service_account import GoogleService

Credentials

Next, we need someway to authenticate with Google. To access the API, you will need the json credentials file (token.json) for your Google Service account. For help creating a Google Service account, please refer to this article (coming soon | Google Article).
- Note: the token.json file should be placed in the same folder as your main.py file.

Google Sheets Example

Lastly, lets demonstrate a simple example - setting a few cells in a Google Sheet (Google Documentation).

Simple example - updating cells in a Google Sheet

With the imported class we will build the service connection and provide it the necessary scopes to access the API.

# Google Sheets
sheet_scopes = ['https://www.googleapis.com/auth/spreadsheets']
gSheetsConnection = GoogleService(sheet_scopes, 'sheets', 'v4')

"""
Other common connectors and their scopes:
"""
# Google Docs
doc_scopes = ['https://www.googleapis.com/auth/documents']
gDocConnection = GoogleService(doc_scopes, 'docs', 'v1')

# Google Drive
drive_scopes = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file']
gDocConnection = GoogleService(drive_scopes, 'drive', 'v3')

Next we need the ID of a Google Sheet. To get this open a Google Sheet and inspect the URL to find the ID:
- https://docs.google.com/spreadsheets/d/<Google Sheet ID>/edit#gid=0

Lastly, create a 2D array of the cells you want to update:

spreadsheet_id = '<Google Sheet ID>' # ID of the Google Sheet
range_name = 'Sheet1!A1:C2' # The range of cells we want to work with
values = [ # A 2D array of values to insert into the above cells
    [2,     3,       '=a1+b1'],
    ['two', 'three', 'five'],
]

data = {
    'values' : values 
}

# Run the update (refer to API doc for details)
gSheetsConnection.getService().spreadsheets().values().update(spreadsheetId=spreadsheet_id, body=data, range=range_name, valueInputOption='USER_ENTERED').execute()

Bringing it all together

import os
from apiclient import discovery
from google.oauth2 import service_account

class GoogleService:
    """
    Build a Google Service Connector. Call .getService() to access the API
    """
    def __init__(self, scopes, api, version, token_file='token.json', token_path=os.getcwd()):
        self.scopes     = scopes
        self.api        = api
        self.version    = version
        self.token_file = token_file
        self.toke_path  = token_path
        self.service    = None

    def getService(self):
        """
            Get the service instance. Will connect if not already existing.
        """
        if self.service:
            return self.service

        secret_file = os.path.join(self.token_path, self.token_file)
        credentials = service_account.Credentials.from_service_account_file(secret_file, scopes=self.scopes)
        self.service = discovery.build(self.service, self.version, credentials=credentials)

        return self.service


# Google Sheets
sheet_scopes = ['https://www.googleapis.com/auth/spreadsheets']
gSheetsConnection = GoogleService(sheet_scopes, 'sheets', 'v4')


spreadsheet_id = '<Google Sheet ID>' # ID of the Google Sheet
range_name = 'Sheet1!A1:C2' # The range of cells we want to work with
values = [ # A 2D array of values to insert into the above cells
    [2,     3,       '=a1+b1'],
    ['two', 'three', 'five'],
]

data = {
    'values' : values 
}

# Run the update (refer to API doc for details)
gSheetsConnection.getService().spreadsheets().values().update(spreadsheetId=spreadsheet_id, body=data, range=range_name, valueInputOption='USER_ENTERED').execute()

Conclusion

Hopefully you have learned something about interacting with Google API's! Although intimidating to connect with, there is a world of possible use cases: auto-generating a Google Doc, pre-filling or running complex Google Sheet equations, moving files around in Google Drive, and much more. Drop a comment below with what you will automate!

Comments

Login to Add comments.