I'm trying to get calendar data from Outlook, so I have the following code:

from O365 import Account, MSGraphProtocol
import datetime as dt

CLIENT_ID = 'f8384621-1095-4519-8999-0c7e616b7bc8'
SECRET_ID = '.s03m-t9u2q_9.Lpim5F.DTL-F1u4MBQy6'

credentials = (CLIENT_ID, SECRET_ID)

protocol = MSGraphProtocol()
#protocol = MSGraphProtocol(defualt_resource='<[email protected]>')
scopes = ['User.Read']
account = Account(credentials, protocol=protocol)

if account.authenticate(scopes=scopes):
   print('Authenticated!')

schedule = account.schedule()
calendar = schedule.get_default_calendar()
events = calendar.get_events(include_recurring=False)
# events = calendar.get_events(query=q, include_recurring=True)


for event in events:
    print(event)

But unfortunately also getting these errors after successful authentication:

Client Error: 403 Client Error: Forbidden for url: https://graph.microsoft.com/v1.0/me/calendar | Error Message: Access is denied. Check credentials and try again.
Traceback (most recent call last):
  File "C:/Users/username/Documents/pycharmproba/main.py", line 18, in <module>
    calendar = schedule.get_default_calendar()
  File "C:\Users\username\Documents\pycharmproba\venv\lib\site-packages\O365\calendar.py", line 1942, in get_default_calendar
    response = self.con.get(url)
  File "C:\Users\username\Documents\pycharmproba\venv\lib\site-packages\O365\connection.py", line 805, in get
    return self.oauth_request(url, 'get', params=params, **kwargs)
  File "C:\Users\username\Documents\pycharmproba\venv\lib\site-packages\O365\connection.py", line 794, in oauth_request
    return self._internal_request(self.session, url, method, **kwargs)
  File "C:\Users\username\Documents\pycharmproba\venv\lib\site-packages\O365\connection.py", line 756, in _internal_request
    raise HTTPError('{} | Error Message: {}'.format(e.args[0], error_message), response=response) from None
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://graph.microsoft.com/v1.0/me/calendar | Error Message: Access is denied. Check credentials and try again.
1

There are 1 answers

0
sid On

You haven't added the scopes to access your calendar events. Add the following scopes to your code and try again.

protocol = MSGraphProtocol()    
scopes = ['User.Read'] 
calendar_scopes = protocol.get_scopes_for('calendar_all')
scopes.extend(calendar_scopes)
account = Account(credentials, protocol=protocol)

if account.authenticate(scopes=scopes):
    print('Authenticated!')