1

I followed the Google Calendar Quickstart guide and my python script can read calendars. But after following the guide for creating new events, my script gets an "Insufficient Permission" error. I'm not sure if it's relevant, but this is a google apps for business account, so all addresses & ids are '@mybusiness.com', not '@gmail.com'

I'm trying to figure out where I've gone wrong. Any help would be appreciated

This is my code:

#!/usr/bin/python
from __future__ import print_function
import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

import datetime

try:
    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'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'
CALENDARID='redacted@redacted.com'
service=None

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.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json')

    store = oauth2client.file.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 read_calendar():
    CAL=service.calendarList().get(calendarId=CALENDARID).execute()
    print("Calendar Summary & Role:",CAL['summary'],CAL['accessRole'])


def insert_event():

    event = {
      'summary': 'Test Insert Event',
      'location': 'Home',
      'description': 'Automagic for the people',
      'start': {
        'dateTime': '2016-05-29T09:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
      'end': {
        'dateTime': '2016-05-29T10:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
      'reminders': {
        'useDefault': True,
      },
    }

    event = service.events().insert(calendarId=CALENDARID, body=event).execute()
    print('Event created: %s' % (event.get('htmlLink')))

def main():
    global service
    """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=CALENDARID, timeMin=now, maxResults=10, singleEvents=True,
        orderBy='startTime').execute()
    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'))
        end = event['end'].get('dateTime', event['end'].get('date'))

        print(start,end,'Summary Redacted')
        print("----------\n")

    read_calendar()
    insert_event()


if __name__ == '__main__':
    main()

This is my output, minus the list of 10 events

$ ./gcal.py
Getting the upcoming 10 events
2016-06-29T09:00:00-04:00 2016-06-29T10:00:00-04:00 Summary Redacted
----------

<..etc... for 10 events, then -->

Calendar Summary & Role: redacted@redacted.com owner
Traceback (most recent call last):
  File "./gcal.py", line 114, in <module>
    main()
  File "./gcal.py", line 110, in main
    insert_event()
  File "./gcal.py", line 79, in insert_event
    event = service.events().insert(calendarId=CALENDARID, body=event).execute()
  File "/usr/lib/python2.7/site-packages/oauth2client/util.py", line 137, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/googleapiclient/http.py", line 760, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/redacted%40redacted.com/events?alt=json returned "Insufficient Permission">
Stephen
  • 11
  • 2
  • Check this SO question [Why is Google Calendar API (oauth2) responding with 'Insufficient Permission'?](http://stackoverflow.com/questions/16970917/why-is-google-calendar-api-oauth2-responding-with-insufficient-permission) and [google plus api: “insufficientPermissions” error](http://stackoverflow.com/questions/16978192/google-plus-api-insufficientpermissions-error) for more information. – KENdi Jun 30 '16 at 07:48

0 Answers0