Search code examples
pythongoogle-apigoogle-calendar-apikeyerror

Why am I getting KeyError here?


I am trying to get the title of all the events in my calendar, so this is the code I took from the Google website

My code:

from Google import Create_Service
import datetime

CLIENT_SECRET_FILE = "secret.json"
API_NAME = 'calendar'
API_VERSION='v3'
SCOPES = ['https://www.googleapis.com/auth/calendar']

service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)

sample = service.events()

page_token = None
while True:
  events = sample.list(calendarId='[email protected]', pageToken=page_token).execute()
  for event in events['items']:
    print(event['summary'])
  page_token = events.get('nextPageToken')
  if not page_token:
    break

The output I got:

Holiday

Holiday

Holiday

Holiday

Holiday

Holiday

Holiday

Holiday

Holiday

KeyError                                  Traceback (most recent call last)
Input In [3], in <module>
      3 events = sample.list(calendarId='[email protected]', pageToken=page_token).execute()
      4 for event in events['items']:
----> 5   print(event['summary'])
      6 page_token = events.get('nextPageToken')
      7 if not page_token:

KeyError: 'summary'

It works fine for the first few events. What's going on?


Solution

  • Your error is telling you that the event retrieved doesn't have a summary key. I'm not sure what the event objects look like exactly, but you can avoid an error like this by checking if the key exists in the first place:

    page_token = None
    while True:
      events = sample.list(calendarId='[email protected]', pageToken=page_token).execute()
      for event in events['items']:
        # .get() returns None instead of throwing an error, 
        # or, as I've done in this case, returns a default variable: "No summary found!"
        summary = event.get("summary", "No summary found!")
        print(summary)
      page_token = events.get('nextPageToken')
      if not page_token:
        break