Uploading a file to onedrive for business with Python

For a Raspberry Pi project that’ll take a number of pictures of my house for an as of yet unknown period of time I’m sharing my very first Python script with you.

All it has to do is upload all files from a given folder to a given Onedrive for Business path, as obviously the Pi can’t store much data on its tiny SD card. You’ll need to register an azure ad app and give it the appropriate permissions. You’ll have to consent to the application once (url format = https://login.microsoftonline.com/common/adminconsent?client_id={client-id}).

Then the schedule below Python script on your Pi, it will retrieve an Azure token without the need for external libraries, parse the directory and upload everything in it to the given onedrive for business URL, simple as that! It can also be used for Sharepoint or Teams by adjusting the path.

import requests 
import json
directory = r"c:\temp\uploads"
data = {'grant_type':"client_credentials", 
        'resource':"https://graph.microsoft.com", 
        'client_id':'XXXXX', 
        'client_secret':'XXXXX'} 
URL = "https://login.windows.net/YOURTENANTDOMAINNAME/oauth2/token?api-version=1.0"
r = requests.post(url = URL, data = data) 
j = json.loads(r.text)
TOKEN = j["access_token"]
URL = "https://graph.microsoft.com/v1.0/users/YOURONEDRIVEUSERNAME/drive/root:/fotos/HouseHistory"
headers={'Authorization': "Bearer " + TOKEN}
r = requests.get(URL, headers=headers)
j = json.loads(r.text)
print("Uploading file(s) to "+URL)
for root, dirs, files in os.walk(directory):
    for filename in files:
        filepath = os.path.join(root,filename)
        print("Uploading "+filename+"....")
        fileHandle = open(filepath, 'rb')
        r = requests.put(URL+"/"+filename+":/content", data=fileHandle, headers=headers)
        fileHandle.close()
        if r.status_code == 200 or r.status_code == 201:
            #remove folder contents
            print("succeeded, removing original file...")
            os.remove(os.path.join(root, filename)) 
print("Script completed")
raise SystemExit
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Rajeev
Rajeev
1 month ago

Hi,
I am using registered email id, but getting user not found, while calling upload api.
Please help, what i am i missing

Geoffroy Givry
Geoffroy Givry
4 months ago

Hi There, Many thanks for this tutorial!
I have one tiny (and stupid!) question. How to I get the
YOURONEDRIVEUSERNAME please? it sounds very silly but I’ve tried my login name from my email account geoff.gi@mycompanyname.onmicrosoft,com: geoff.gi
And it didn’t work. Did I miss anything?
Thanks a lot for your help!

Geoff

Joris
Joris
5 months ago

Good stuff! The script completed successfully (status code 200) for my test files. Unfortunately the files are nowhere to be found in OneDrive for Business. Any idea what I am doing wrong? (Trying to upload to the root folder). Also, would you have pointers on how to limit the App’s access to only one specific folder (write only)? Thanks for sharing your script!

Thierry
7 months ago

Short and sweet… Perfect

Gajendra Patidar
Gajendra Patidar
9 months ago

I’m not able to send big file like 25MB

Wa Wa
Wa Wa
9 months ago

Great script ! Thanks a lot