Integrating Google Calendar to Django - carloramferrer/Django-AWS GitHub Wiki

Adding Calendar Events using Google Calendar API (Python)

Setup Service Account

Before you can start, you need to setup your service account and add it to your calendar. These and all other information in this page are included in their documentation.

API Authentication

Most API calls require authentication methods such as API keys or Authorized API access (OAuth). Here we will use the latter. OAuth 2.0 is a library which allows users to grant applications access before they can create API calls.

Scopes

When requesting data, the application must add one or more scopes to its request. This must be approved by the user.

Builds, Services and Methods

Then, you need to create a service object using the build() function based on the methods specific to the API. This service shall allow you to call a method from its collection. Here, we will try to call the insert method of Google Calendar API to add an event to a user's calendar

Another tutorial by Indian Pythonista in Youtube also demonstrates a more detailed process. This can also be seen in Google Calendar API docs for Python.

The code below is a snippet from an example by pasql in StackOverflow.

import os
from datetime import timedelta
import datetime
import pytz

import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

service_account_email = '[email protected]'

CLIENT_SECRET_FILE = 'creds.p12'

SCOPES = 'https://www.googleapis.com/auth/calendar'
scopes = [SCOPES]

def build_service():
    credentials = ServiceAccountCredentials.from_p12_keyfile(
        service_account_email=service_account_email,
        filename=CLIENT_SECRET_FILE,
        scopes=SCOPES
    )

    http = credentials.authorize(httplib2.Http())

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

    return service


def create_event():
    service = build_service()

    start_datetime = datetime.datetime.now(tz=pytz.utc)
    event = service.events().insert(calendarId='<YOUR EMAIL HERE>@gmail.com', body={
        'summary': 'Foo',
        'description': 'Bar',
        'start': {'dateTime': start_datetime.isoformat()},
        'end': {'dateTime': (start_datetime + timedelta(minutes=15)).isoformat()},
    }).execute()

    print(event)