Listing Files form OneDrive Using Python

Copper Contributor

Hello,

 

I am trying to build an App in Python that automate files creation and deletion in OneDrive. I decided to use Microsoft  Graph API for this. I wrote the following script to get started.

 

import msal
import requests
import json

# Define the MSAL application configuration
client_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
authority = 'https://login.microsoftonline.com/common'
scope = ['https://graph.microsoft.com/.default']

# Create a PublicClientApplication object
app = msal.PublicClientApplication(client_id=client_id, authority=authority)

# Check if the user has already signed in
accounts = app.get_accounts()
if accounts:
    # Get an access token silently
    result = app.acquire_token_silent(scope, account=accounts[0])
else:
    # Sign in and get an access token interactively
    result = app.acquire_token_interactive(scope)

# Get the access token from the result
access_token = result['access_token']
headers = {'Authorization': 'Bearer ' + access_token,
           'Content-Type': 'application/json'}

# url = "https://graph.microsoft.com/v1.0/me" # works just fine
url = "https://graph.microsoft.com/v1.0/me/drive/root/children"

# send a request
response = requests.get(url,headers=headers)

# check the status code of the response
if response.status_code == requests.codes.ok:
    print(response.json())
else:
    # Print the error message if the request failed
    print(f'Request failed with status code: {response.status_code}')
    print(response.json())

 

Fetching the profile information using the URL in line 27 works as expected. However, listing the drive items using the URL in Line 28 gives the following error:

 

{'error': {'code': 'itemNotFound', 'message': 'Item not found', 'innerError': {'date': '2023-04-07T11:58:04', 'request-id': '.........', 'client-request-id': '.........'}}}

 

This is the App permission:

DuhaiAlshukaili_0-1680869889875.png

 

Any idea what is going on?

 

 

1 Reply

@DuhaiAlshukaili 
Don't you need to Grant admin consent, so that you have green tick under Status?

Slashbit_0-1681038943212.png