I have a python code to call a graph API and browse directory on sharepoint. The directory has 120GB of files and needs hours to scan. However, what I have observed is the script just shows as running on Visual Studio code and no further execution happens. I am printing the files names in the loop and it stops to put the file names after an hour.
Can it be because of Token getting expired after an hour? If yes, why I do not get an error stating the token to be invalid?
# Define imports
import requests
# Copy access_token and specify the MS Graph API endpoint you want to call, e.g. 'https://graph.microsoft.com/v1.0/groups' to get all groups in your organization
#access_token = '{ACCESS TOKEN YOU ACQUIRED PREVIOUSLY}'
url = "[URL TO THE SHAREPOINT]"
headers = {
'Authorization': access_token
}
consentfilecount=0
clientreportcount = 0
graphlinkcount = 0
while True:#
#print(graph_result.json()['@odata.nextLink'])
graph_result = requests.get(url=url, headers=headers)
if ('value' in graph_result.json()):
for list in graph_result.json()['value']:
if(("Client Consent Form").lower() in list["name"].lower()):
consentfilecount +=1
print(list["name"])
if(("Final Client Report").lower() in list["name"].lower()):
clientreportcount +=1
print(list["name"])
#print(graph_result.json())
if('@odata.nextLink' in graph_result.json()):
url = graph_result.json()['@odata.nextLink']
graphlinkcount += 1
else:
break
print(consentfilecount)
2
Answers
Yes, the default lifetime of an Access Token for Microsoft Graph is between 60 and 90 minutes so for longrunning tasks you should check if it’s expiring and refresh it in time (or handle the error accordingly).
The behavior you describe is almost certainly due to the fact that the bearer token you seem to be using is indeed valid only for an hour or so.
By default,
requests
does not raise exceptions based solely on HTTP status codes to allow developers to choose how they want to handle such scenarios. In your case, yourwhile True:
loop simply continues running, successfully parsing the JSON structure that comes back from the error response but never actually hitting any of your conditions within the block.If you do want your script to throw an exception on non-successful HTTP response codes, you can add a call to
raise_for_status()
:However if your code is expected to normally run for periods in excess of your token’s validity, you should probably work the proper OAuth refresh flows into your code to prevent such errors from occurring.