Fetch upcoming 10 events of user using google calendar API in Python


* Python command-line application that makes requests to the Google Calendar API to fetch upcoming 10 events.

The entire feature can be achieve in three steps.

  1. Setting up Google Calendar API.
  2. Installing google client library.
  3. Creating python script.

Let’s Get Started :

Setting up Google Calendar API.

  1. Go to google console.
  2. Create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.
  3. On the Add credentials to your project page, click the Cancel button.
  4. Select the OAuth consent screen tab. Select an Email address, enter a Product name and click the Save button.Selection_453.png
  5. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
  6. Select the application type Other, enter the name “Google Calendar API Quickstart”, and click the Create button.
  7. Click OK to dismiss the resulting dialog.
  8. Click the file_download (Download JSON) button to the right of the client ID.Selection_455
  9. Move this file to your working directory and rename it client_secret.json.

Installing google client library. 

virtualenv googlecalendar
source googlecalendar/bin/activate
pip install --upgrade google-api-python-client

Google Calendar API Script

Create Python file name as gquickstart.py.

Now edit the file and add following code.

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

import datetime

    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

        Credentials, the obtained credential.
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
    credential_path = os.path.join(credential_dir,

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    """Shows basic usage of the Google Calendar API.

    Creates a Google Calendar API service object and outputs a list of the next
    10 events on the user's calendar.
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    eventsResult = service.events().list(
        calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
    events = eventsResult.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])

if __name__ == '__main__':

To run this Script

python quickstart.py

Next, Copy the URL from the console and manually open it in your browser.

If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization. Click the Accept button. Now you will be redirect to page which will contain the verification code. Copy this code and paste it in the terminal.

You will be shown list of upcoming 10 events in your calendar.

Hope it helped.

Soon will be coming up with django package which will enable the user to view, create, update his calendar without visiting google.com. Github.

*You will need google account. Please keep it handy


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s