Monday, 19 June 2023

Python x Sharepoint - CreateUploadSession

I'm trying to write files to Sharepoint using Microsoft Graph API (CreateUploadSession).

I'm able to read from sharepoint easily and already have done the process to request the token.

But when I'm trying to use this API endpoint, I'm getting an error

requests.get(f'{ENDPOINT}/drives/{drive_id}/root:/{folder_url}', headers=headers)

import requests
import msal
import atexit
import os.path
import urllib.parse
import os


TENANT_ID = '<your tenant id>'
CLIENT_ID = '<your application id>'
SHAREPOINT_HOST_NAME = 'yourcompany.sharepoint.com'
SITE_NAME = '<your site name>'

AUTHORITY = 'https://login.microsoftonline.com/' + TENANT_ID
ENDPOINT = 'https://graph.microsoft.com/v1.0'    
filename = 'test_file.txt'
folder_path = "C:/Users/svcAlteryx-DEV/Desktop"

folder_url = urllib.parse.quote(folder_path)
result = requests.get(f'{ENDPOINT}/drives/{drive_id}/root:/{folder_url}', headers=headers)
print(f'{ENDPOINT}/drives/{drive_id}/root:/{folder_url}')
result.raise_for_status()


HTTPError: 400 Client Error: Bad Request for url: https://graph.microsoft.com/v1.0/drives/b!RISMyiDdukGGGNeDPsCAu_mfncDFdCNCjwSApVwoJ7R2lYZfKplTR4Lv3IkATh-p/root:/C%3A/Users/svcAlteryx-DEV/Desktop

Any ideas what I might be doing wrong? The (drive_Id) was gathered by using this call (response 200):

result = requests.get(f'{ENDPOINT}/sites/{site_id}/drive', headers=headers)
result.raise_for_status()
drive_info = result.json()
drive_id = drive_info['id']

After that I'll proceed with this:

folder_info = result.json()
folder_id = folder_info['id']

file_url = urllib.parse.quote(filename)
result = requests.post(
    f'{ENDPOINT}/drives/{drive_id}/items/{folder_id}:/{file_url}:/createUploadSession',
    headers=headers,
    json={
        '@microsoft.graph.conflictBehavior': 'replace',
        'description': 'A large test file',
        'fileSystemInfo': {'@odata.type': 'microsoft.graph.fileSystemInfo'},
        'name': filename
    }
)
result.raise_for_status()
upload_session = result.json()
upload_url = upload_session['uploadUrl']


from Python x Sharepoint - CreateUploadSession

No comments:

Post a Comment