Downloading Sharepoint Files with Python

In case of automating file downloads from Sharepoint, here I will be sharing the steps to download files from Sharepoint folder to your local disk using Python.

First, we need to register the Sharepoint site and generate a Client Id and Client Secret for the Sharepoint site which will be used for authentication.

For registering, go to <site url>/_layouts/15/AppRegNew.aspx.

For example, my sharepoint site is https://mysharepoint.com/sites/DownloadFiles/. So, I will add ‘/_layouts/15/AppRegNew.aspx’ at the end of the URL and it will be https://mysharepoint.com/sites/DownloadFiles/_layouts/15/AppRegNew.aspx.

Then you will be directed to the below page.

1

Click on Generate button and a Client ID and Client Secret will be generated. Enter the other details like App Domain and Redirect URL and click on Create button.

For Example,
Title:  Download
App Domain: www.google.com
Redirect URL: https://www.google.com

Make sure you keep a note of your Client ID and Client Secret, since it will be used for authentication. Next step is to give necessary permission for your Sharepoint Site. For granting permissions,

Go to <site url>/_layouts/15/appinv.aspx.

In my case it would be, https://mysharepoint.com/sites/DownloadFiles/_layouts/15/ appinv.aspx.

Enter your Client ID in the App Id textbox and click Lookup button. Then paste the below xml code under Permission Request XML box.

<AppPermissionRequests AllowAppOnlyPolicy=”true”><AppPermissionRequest Scope=”http://sharepoint/content/sitecollection” Right=”FullControl”/></AppPermissionRequests>

2

Click Create and you will be asked whether you trust this source.  Click on Trust it and its done.

3

Now you can use the below python code to download files from the registered Sharepoint site to your local disk.

4Replace the URL with your Site URL and corresponding Client ID and Client Secret values. Replace the following line with the filename that you want to download.

File.open_binary(ctx,/sites/DownloadFiles/Shared%20Documents/<yourfile with extension>”)

And that’s it, you’ve successfully downloaded the file using python. Keep a note, you need the python module Office365-REST-Python-Client to run the above code.

References: