Search code examples
pythongoogle-apihttp-status-code-404google-calendar-apigoogle-api-python-client

How can I get Google Calendar API status_code in Python when get list events?


I try to use Google Calendar API

events_result = service.events().list(calendarId=calendarId,
                                          timeMax=now,
                                          alwaysIncludeEmail=True,
                                          maxResults=100, singleEvents=True,
                                          orderBy='startTime').execute()

Everything is ok, when I have permission to access the calendarId, but it will be errors if wrong when I don't have calendarId permission.

I build an autoload.py function with schedule python to load events every 10 mins, this function will be stopped if error come, and I have to use SSH terminal to restart autoload.py manually So i want to know:

How can I get status_code, example, if it is 404, python will PASS


Solution

  • Answer:

    You can use a try/except block within a loop to go through all your calendars, and skip over accesses which throw an error.

    Code Example:

    To get the error code, make sure to import json:

    import json
    

    and then you can get the error code out of the Exception:

    calendarIds = ["calendar ID 1", "calendar ID 2", "calendar Id 3", "etc"]
    
    for i in calendarIds:
        try:
            events_result = service.events().list(calendarId=i,
                                              timeMax=now,
                                              alwaysIncludeEmail=True,
                                              maxResults=100, singleEvents=True,
                                              orderBy='startTime').execute()
        except Exception as e:
            print(json.loads(e.content)['error']['code'])
            continue
    

    Further Reading: