Friday, October 3, 2014

Introduction to the Google Calendar API (HOWTO)

I have used Google Calendars to schedule and control a number of projects (eg. sprinkler system, alarm clock, etc) .  The following How To will get you started.  You will of course need a google account.

Create Project

1) Start by visiting the Google Developers Console

and create a new project.

2) Select the project and navigate on the left menu to APIs & auth then APIs and enable Calendar API for this project.  You can disabled all other APIs if you only need Calendar access.

3) Next, select the Consent screen menu option from the APIs & auth menu.  Enter a Product Name and select an Email Address.  If you do not do this step, you will get a Error: invalid_client error later on.

4) Next, select the Credentials menu option from the APIs & auth menu.  Under OAuth select Create new Client ID.

5) For the Create Client ID select Installed application for Application Type and select Other for Installed Application Type and finally click the Create Client ID button.

6) After the ID has finished being created, click the Download JSON button.  Save and rename the file as something simple like client_secret.json.

This json file contains your API credentials needed to access the Google Calendar APIs.

Install Google API Libraries

1) Install the Google API Libraries using Python's PIP installer:
$ sudo pip install --upgrade google-api-python-client

gflags may or may not be needed, depending on what code you use: (may be optional)
$ sudo pip install --upgrade python-gflags

If you would prefer alternatives, view the Google APIs Client Library for Python page.

Authorize Application

Next we will need to run our application and authorize it against the desired account.

1) Clone my sample code:
# git clone

The sample code is just a slight modification from the Getting Started Sample Code.  The Google sample code has some outdated code that will throw some obsoleted warnings.

2) The application has not been authorized to an account yet.  Run the application once and you will be asked to paste a validation URL into your browser.  Login to your desired target account (with the calendars you want to access) and then paste the validation URL into your browser.

For convenience I have a script that is the same script as the script, but terminates after authorization.  You can run any of the scripts to complete this authorization step.

The is pretty simple:
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import OAuth2WebServerFlow
from import run_flow
from oauth2client.client import flow_from_clientsecrets

def main():
    scope = ''
    flow = flow_from_clientsecrets('client_secret.json', scope=scope)

    storage = Storage('credentials.dat')
    credentials = storage.get()

    class fakeargparse(object):  # fake argparse.Namespace
        noauth_local_webserver = True
        logging_level = "ERROR"
    flags = fakeargparse()

    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage, flags)

if __name__ == '__main__':

You may notice the "fakeargparse" code. The run_flow() call wants the flags to be set from the parameters pulled from argparse. I think that is overkill for what I needed, so I just created a fake container so run_flow() wouldn't complain.

Run the script to collect the application authorization.
$ python
Go to the following link in your browser:

Enter verification code:

3) Copy the URL into the browser and accept the permissions.

4) You will be presented with a code, to which you will then enter back into the prompt of the application.  The authorization will be stored in the credentials.dat file for future requests.
$ python
Go to the following link in your browser:

Authentication successful.

Now that we have our API credentials and are authorized to access an account, we can begin to play with the Google Calendars.

View Upcoming Events

The script builds off of the script, cycles through the next few upcoming calendar events and displays the event titles.
    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage, flags)

    http = httplib2.Http()
    http = credentials.authorize(http)
    service = build('calendar', 'v3', http=http)

    print "Upcoming Events:"
    request ='primary')
    while request != None:
        response = request.execute()
        for event in response.get('items', []):
            print event.get('summary', 'NO SUMMARY')
        request =, response)

This script defaults to the primary calendar associated with the account.

Calendar ID

The previous script defaults to the primary calendar associated with the account.  If you wish to specify an alternate calendar, you will need the Calendar ID.  A calendar's ID can be found on the Calendar Details setting page (same page you can change a calendar's name on).  Look for the Calendar Address line, and the Calendar ID will be in the parenthesis.  It will look something like "".

Next 12 Hours of Events

Finally, to specify a time range for events, I use the following code in my script.  This code will collect the next 12 hours worth of events.

    service = build('calendar', 'v3', http=http)

    # get the next 12 hours of events
    epoch_time = time.time()
    start_time = epoch_time - 3600  # 1 hour ago
    end_time = epoch_time + 12 * 3600  # 12 hours in the future
    tz_offset = - time.altzone / 3600
    if tz_offset < 0:
        tz_offset_str = "-%02d00" % abs(tz_offset)
        tz_offset_str = "+%02d00" % abs(tz_offset)
    start_time = datetime.datetime.fromtimestamp(start_time).strftime("%Y-%m-%dT%H:%M:%S") + tz_offset_str
    end_time = datetime.datetime.fromtimestamp(end_time).strftime("%Y-%m-%dT%H:%M:%S") + tz_offset_str

    print "Getting calendar events between: " + start_time + " and " + end_time

    events ='primary', timeMin=start_time, timeMax=end_time, singleEvents=True).execute()singleEvents=True).execute()
    for event in events['items']:
        print event["summary]

And this is the basis for the code I use to schedule my sprinkler system with.