DEV Community

Cover image for How to get started with Google Calendar API using Python with Examples
karenapp
karenapp

Posted on • Originally published at karenapp.io

How to get started with Google Calendar API using Python with Examples

Google Calendar offers one of the most convenient and popular ways to manage schedule,
events, meetings, or even plan out your holiday events. A few things you think will
be straightforward end up being complicated for customised need. The Google Calendar
API lets you automate your calendar, for those custom needs.

1. How to Create a project in Google Developer Console?

To kick things off lets head Google Developers Console and create a new project.
We name the project as Automating Calendar, further to it, get the credentials.

2. Set up the Google API Service

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/calendar']

CREDENTIALS_FILE = 'credentials.json'

def get_calendar_service():
    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_FILE, 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('calendar', 'v3', credentials=creds)
    return service

2. How to Fetch list of all Calendars from a User Account using Calendar API

Let us create a file with name list_calendars.py in the same directory as that of cal_setup.py with the snippet below:

from cal_setup import get_calendar_service

def main():
   service = get_calendar_service()
   # Call the Calendar API
   print('Getting list of calendars')
  calendars_result = service.calendarList().list().execute()

   calendars = calendars_result.get('items', [])

   if not calendars:
       print('No calendars found.')
   for calendar in calendars:
       summary = calendar['summary']
       id = calendar['id']
       primary = "Primary" if calendar.get('primary') else ""
       print("%s\t%s\t%s" % (summary, id, primary))

if __name__ == '__main__':
   main()

The above code is calling the Calendar API with the credentials that have already been setup, it will fetch all the calendars.

When the above code is run for the first time, a google auth link will be opened in default browser seeking permission to access the calendar, after the consent is provided a token is saved which can be used for making requests in future to the Google Calendar API.

Once the code has run, in the terminal you will see on the console the names of all the calendars that you have created.

If you want to do more things, we have created an in-depth article with screenshots - how to automate google calendar with python

The entire source code can be found here on our github.

Top comments (0)