Can't access Microsoft To Do list using the MS Graph API

869 views Asked by At

I try to make programm in python to add appointments to Microsoft To Do I'm using the Microsoft Graph API with following code:

import requests
import msal
import atexit
import os.path

TENANT_ID = 'X
CLIENT_ID = 'Y'


AUTHORITY = 'https://login.microsoftonline.com/' + TENANT_ID
ENDPOINT = 'https://graph.microsoft.com/v1.0'

SCOPES = [
    'Files.ReadWrite.All',
    'Sites.ReadWrite.All',
    'User.Read',
    'User.ReadBasic.All',
    'Tasks.ReadWrite'
]


cache = msal.SerializableTokenCache()

if os.path.exists('token_cache.bin'):
    cache.deserialize(open('token_cache.bin', 'r').read())

atexit.register(lambda: open('token_cache.bin', 'w').write(cache.serialize()) if cache.has_state_changed else None)

app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY, token_cache=cache)

accounts = app.get_accounts()
result = None
if len(accounts) > 0:
    result = app.acquire_token_silent(SCOPES, account=accounts[0])

if result is None:
    flow = app.initiate_device_flow(scopes=SCOPES)
    if 'user_code' not in flow:
        raise Exception('Failed to create device flow')

    print(flow['message'])

    result = app.acquire_token_by_device_flow(flow)
   
if 'access_token' in result:
    print(result['access_token'])
    result = requests.get(f'https://graph.microsoft.com/v1.0/me/todo/lists', headers={'Authorization': 'Bearer ' + result['access_token']})
    print(result.json())

else:
    raise Exception('no access token in result')


This is the error I get:

{'error': {'code': 'UnknownError', 'message': 'The service is unavailable.', 'innerError': {'date': '2022-01-25T18:52:03', 'request-id': 'X', 'client-request-id': 'X'}}}

I tried to google the error but I didn't found any solution that worked for me.

2

There are 2 answers

8
vicky kumar On

Just for Curiosity ,I would like to know have you entered your TENANT_Id and CLIENT_ID in place of "X" and "Y". if yes and still its not working.

Could you please try to run the URL - https://graph.microsoft.com/v1.0/me/todo/lists on Graph explorer and postman. let us know if you are still facing the issue.

3
vicky kumar On

could you please check your token expiry time (exp), might be it got expired. Go to jwt.ms to check token details, find the attached image to see where to find token time. check exp time

If the token got expired ,please the docs get new token.