DEV Community

Cover image for Google Calendar API with Python
Nelson Adonis Hernández
Nelson Adonis Hernández

Posted on • Updated on

Google Calendar API with Python

In this example we will see the main methods to interact with Google Calendar API

Dependencies

pip3 install google-api-python-client google-auth-httplib2 google-auth-oauthlib
Enter fullscreen mode Exit fullscreen mode

Credentials of Google Cloud in JSON

Credentials

{
  "web": {
    "client_id": "",
    "project_id": "",
    "auth_uri": "",
    "token_uri": "",
    "auth_provider_x509_cert_url": "",
    "client_secret": "",
    "redirect_uris": ["http://localhost/"]
  }
}
Enter fullscreen mode Exit fullscreen mode

Create Service

This allows us to interact with all Google APIs, in this case Calendar

token.txt is generated automatically

from os import path
import pickle
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# IF YOU MODIFY THE SCOPE DELETE THE TOKEN.TXT FILE
SCOPES = ['https://www.googleapis.com/auth/calendar.events',
          'https://www.googleapis.com/auth/calendar']

# THE TOKEN.TXT FILE STORES UPDATE AND USER ACCESS TOKENS

def get_crendetials_google():
    # OPEN THE BROWSER TO AUTHORIZE
    flow = InstalledAppFlow.from_client_secrets_file("creds.json", SCOPES)
    creds = flow.run_local_server(port=0)

    # WE SAVE THE CREDENTIALS
    pickle.dump(creds, open("token.txt", "wb"))
    return creds

def get_calendar_service():
    creds = None
    if path.exists("token.txt"):
        creds = pickle.load(open("token.txt", "rb"))
    # IF IT EXPIRED, WE REFRESH THE CREDENTIALS
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            creds = get_crendetials_google()

    service = build("calendar", "v3", credentials=creds)

    return service
Enter fullscreen mode Exit fullscreen mode

Template

{
  "summary": "Important event!",
  "location": "Virtual event (Slack)",
  "description": "This a description",
  "start": {
    "dateTime": "2021-12-10T10:00:00",
    "timeZone": "America/El_Salvador"
  },
  "end": {
    "dateTime": "2021-12-10T11:00:00",
    "timeZone": "America/El_Salvador"
  },
  "attendees": [{ "email": "email@gmail.com" }],
  "reminders": {
    "useDefault": false,
    "overrides": [
      { "method": "email", "minutes": 30 },
      { "method": "popup", "minutes": 10 }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Create Event


service = get_calendar_service()


def create_event(template: dict):
    try:
        response = service.events().insert(calendarId="primary", body=template).execute()
        return response
    except Exception as e:
        return e.message
Enter fullscreen mode Exit fullscreen mode

Get Event

def get_event(eventId: str):
    try:
        response = service.events().get(calendarId="primary", eventId=eventId).execute()
        return response
    except Exception as e:
        return e.message
Enter fullscreen mode Exit fullscreen mode

Update Event

def update_event(eventId: str, template: dict):
    try:
        response = service.events().update(calendarId='primary',
                                           eventId=eventId, body=template).execute()
        return response
    except Exception as e:
        return e.message

Enter fullscreen mode Exit fullscreen mode

Delete Event

def delete_event(eventId: str):
    try:
        response = service.events().delete(calendarId="primary", eventId=eventId).execute()
        return response
    except Exception as e:
        return e.message
Enter fullscreen mode Exit fullscreen mode

Example in GitHub Gist
https://gist.github.com/nelsoncode019/7b29221e635588d0b267ce7946d945c9

Discussion (1)

Collapse
adwaithrajesh profile image
Adwaith Rajesh

Thanks