I’m trying to upload a pdf file using Onedrive API with a python script.
However I’m getting a Error 400 with message of “Unsupported use of colon”.
I’m using Onedrive Personal and the endpoint URL api.onedrive.com
should be correct. I have also read that large file might cause Error 400 as well but my .pdf file size is only 300kb.
import requests
from msal import ConfidentialClientApplication
onedrive_id = "1234" # (client) ID
onedrive_secret = "5678"
authority_url = "https://login.microsoftonline.com/consumers"
onedrive_scopes = ["https://graph.microsoft.com/.default"]
file_name = "Sample.pdf"
target_folder = "/My files/Sample folder"
def onedrive_access():
app = ConfidentialClientApplication(
onedrive_id,
authority=authority_url,
client_credential=onedrive_secret
)
result = app.acquire_token_for_client(scopes=onedrive_scopes)
if 'access_token' in result:
return result['access_token']
else:
raise Exception('Could not obtain access token')
def onedrive_upload(access_token, file_path, file_name, target_folder):
endpoint = f'https://api.onedrive.com/v1.0/me/drive/root:/{target_folder}/{file_name}:/content'
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/pdf'
}
with open(file_path, 'rb') as file:
response = requests.put(endpoint, headers=headers, data=file)
if response.status_code == 201:
print(f'File {file_name} uploaded successfully to {target_folder}')
else:
print(f'Failed to upload {file_name} to {target_folder}: {response.status_code} - {response.text}')
onedrive_token = onedrive_access()
onedrive_upload(onedrive_token, file_path, file_name, target_folder)