Blog

How to Upload a File to SharePoint On-Premises Using Python

How to Upload a File to SharePoint On-Premises Using Python

There are several tools out there for interacting with SharePoint through a Python script, but today, I am going to demonstrate a very simple way to upload a file to your SharePoint environment with minimal overhead. This can be useful for users running on Linux environments, such as a Raspberry PI, who want to script some functionality.

Using Octoprint to Monitor 3D Printing

I recently set up a tool called Octoprint on a Raspberry Pi, and am using it to control and monitor the 3D printer here at DMC.

The tool generates timelapses after each print, and it started to take up a lot of space on the Pi’s storage.

I used the following script to take newly rendered timelapses and upload them to SharePoint. This allows users to easily access their print timelapses and frees space on the pi.

Setup

You will need to install the requests package and NTLM authentication package on your environment. In a Linux environment, type the following commands:

pip install requests

pip install requests_ntlm

Python Script

#Import required packages
import sys
import requests
from requests_ntlm import HttpNtlmAuth

#Read filename (relative path) from command line
fileName = sys.argv[1]

#Enter your SharePoint site and target library
sharePointUrl = 'https://your.sharepointsite.com'
folderUrl = '/Your/SharePoint/DocumentLibrary'

#Sets up the url for requesting a file upload
requestUrl = sharePointUrl + '/_api/web/getfolderbyserverrelativeurl(\'' + folderUrl + '\')/Files/add(url=\'' + fileName + '\',overwrite=true)'

#Read in the file that we are going to upload
file = open(fileName, 'rb')

#Setup the required headers for communicating with SharePoint 
headers = {'Content-Type': 'application/json; odata=verbose', 'accept': 'application/json;odata=verbose'}

#Execute a request to get the FormDigestValue. This will be used to authenticate our upload request
r = requests.post(sharePointUrl + "/_api/contextinfo",auth=HttpNtlmAuth('Domain\\username','password'), headers=headers)
formDigestValue = r.json()['d']['GetContextWebInformation']['FormDigestValue']

#Update headers to use the newly acquired FormDigestValue
headers = {'Content-Type': 'application/json; odata=verbose', 'accept': 'application/json;odata=verbose', 'x-requestdigest' : formDigestValue}

#Execute the request. If you run into issues, inspect the contents of uploadResult
uploadResult = requests.post(requestUrl,auth=HttpNtlmAuth('Domain\\username','password'), headers=headers, data=file.read())

Browse to your SharePoint site, and you should now see the newly uploaded file.

Learn more about DMC's SharePoint Consulting Services and Digital Workplace Solutions team. Contact us for your next custom SharePoint project.

Comments

Alexandre Willame
# Alexandre Willame
Thank you for the post.

Quick question: for download, what is typically the function to use?

Thanks,
Curtis Weir
# Curtis Weir
Hi Casey,

After uploading the document, you'll need to make a separate call to update the document metadata. The "uploadResult" variable should contain the ID of the new document. Please use the following resource to update the list item (pass the ID to the url)

https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-lists-and-list-items-with-rest#update-list-item
Casey
# Casey
Hello Curtis,

I realize this was posted a year ago, but I hope you can offer me a little guidance. I was able to work through this snippet and get a document uploaded to SharePoint, now I am looking for how to send over the other fields we have for the document library. Any help would be greatly appreciated.

Casey

Curtis
# Curtis
Hi Afzal,

Sounds like there is an issue when you are attempting to get SharePoint context info (line 23). Please examine the value of r.json() to see what the specific error is. It is likely due to invalid credentials.
Afzal
# Afzal
Getting Key Error ; 'd' in FormdigestValue


formDigestValue = r.json()['d']['GetContextWebInformation']['FormDigestValue']
KeyError: 'd'

Post a comment

Name (required)

Email (required)

CAPTCHA image
Enter the code shown above:

Related Blog Posts