Search code examples
pythonsharepoint-rest-api

Download all files in a Sharepoint folder using Python?


I have a Sharepoint folder, where every week several files would be dumped. Using python, I would like to download all the files from to a local folder location, do some transformations and upload a single consolidated file back to different location on Sharepoint. But whatever calls I am making, returns an empty JSON file.

Here is the code I have tried till now:

import sharepy
sess = sharepy.connect(site='company.sharepoint.com', username='username', password='password')

site = r'https://company.sharepoint.com/'
path = r'/some-site/Documents/Folder1/Folder2/Folder3/'

r = sess.get(site + """_api/web/GetFolderByServerRelativeUrl('"""+path+"""')/Files""")
r
r.json()['d']['results']

r object is a <Response [200]>.I want to download all the files in Folder3, but it returns empty. If I goto the Sharepoint website, I can see all the files using the same username used to create sess object.

I am getting path variable from the bottom of the details pane. I have tried many other options than GetFolderByServerRelativeUrl, but couldn't seems to be working.

I am new to Python and have no clue about Rest APIs.

Thank you for your help.


Solution

  • You need to get a list of files

    # Get list of all files and folders in library
    files = s.get("{}/_api/web/lists/GetByTitle('{}')/items?$select=FileLeafRef,FileRef"
              .format(site, library)).json()["d"]["results"]
    

    for the complete solution, check this:

    https://github.com/JonathanHolvey/sharepy/issues/5