TUTORIAL

How to connect Abstra with Google API

Connect your Abstra project to the many Google services, including Google Calendar and Gmail. Automate various processes by fetching and writing data from their APIs.

Connecting Abstra to Google APIs is as simple as following the steps required to use the Google API with Python, and then using a few best practices to work within Abstra.


Since Google API has a great Python support, all the code in the examples will work in Abstra.

Step 1: Create a project in Google Workspaces and generate the credentials file

Follow the Python quickstart guide on Google Workspaces for the desired API, for instance, the Google Calendar API Python Quickstart Guide. You can use the example code directly on Abstra's Editor in an Abstra Script.

Google Calendar API Python Quickstart Guide

If the Google API setup is made correctly, the code will run successfully.

Code from Google Tutorial running on Abstra

Step 2: Adapt the code to follow suggested practices

In the Google Tutorial, they suggest saving the credentials in a credentials.json file. Instead of a credentials file, we suggest saving the credentials json in a .env file and we certify this file is excluded from your versioning tool. This way you'll:

  1. Guarantee you are not publishing the credentials in your repository;
  2. Be able to setup the production environment easily by configuring the environment variables in the project page on the Abstra Cloud Console.

Your.env file should look like this:


GOOGLE_CRED_JSON={"installed":{"client_id":"[CLIENT_ID]","project_id":"[PROJECT_ID]","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"[CLIENT_SECRET]","redirect_uris":["http://localhost"]}}

In the Python code, you'll get the env var value


import os
import json

# ...
# Define the SCOPES required in the desired API

credentials_json = json.loads(os.getenv("GOOGLE_CRED_JSON") or "{}")
flow = InstalledAppFlow.from_client_config(credentials_json, SCOPES)
creds = flow.run_local_server(port=0)

Final code after adapting


import datetime
import json
import os
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

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]


def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    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:
            credentials_json = json.loads(os.getenv("GOOGLE_CRED_JSON") or "{}")
            flow = InstalledAppFlow.from_client_config(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("calendar", "v3", credentials=creds)

        # Call the Calendar API
        now = datetime.datetime.utcnow().isoformat() + "Z"  # 'Z' indicates UTC time
        print("Getting the upcoming 10 events")
        events_result = (
            service.events()
            .list(
                calendarId="primary",
                timeMin=now,
                maxResults=10,
                singleEvents=True,
                orderBy="startTime",
            )
            .execute()
        )
        events = events_result.get("items", [])

        if not events:
            print("No upcoming events found.")
            return

        # Prints the start and name of the next 10 events
        for event in events:
            start = event["start"].get("dateTime", event["start"].get("date"))
            print(start, event["summary"])

    except HttpError as error:
        print(f"An error occurred: {error}")


main()

Step 3: Configure env vars in production

To configure the production env vars, go to the Abstra Cloud Console, select the organization and project, select the Env Vars item from the navigation menu, and add the production credentials.

Abstra Cloud - Env Vars page with the google credentials

You're set, ready to integrate your automations and processes with all of Google services.