3
votes

I am trying to download files from sharepoint through REST API using Python. Here is my code:

import requests
from requests_ntlm import HttpNtlmAuth

req = requests.get("http://sharepoint/sites/publishing/sales/_api/web/getfilebyserverrelativeurl('\Documents\Folder\data_04202015.csv')",auth=HttpNtlmAuth('domain\\username','password'))
print req.status_code

If the requested url is "http://sharepoint/sites/publishing/sales/_api/web" the return code will be 200 ok, but when trying with GetFileByServerRelativeUrl, it will return 400.

1
I don't know this but do you need to specify the drive? a.k.a. C:. If not i'm curious as to why?SirParselot
@SirParselot we don't need to specify the drive... it's like a web host..Robert

1 Answers

3
votes

Finally I am able to access those files using a sharepoint library

The file path is like: http://sharepoint/sites/publishing/sales/Sales_Distribution/Data/record.csv

Please note that if you are trying to access files under a folder, you have to specify the path roots from /sites/...

from sharepoint import SharePointSite, basic_auth_opener
import urllib2
from ntlm import HTTPNtlmAuthHandler

user = 'domain\username'
password = "password"

server_url = "http://sharepoint/"
site_url = server_url + "sites/publishing/sales/"

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, site_url, user, password)
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)

opener = urllib2.build_opener(auth_NTLM)
urllib2.install_opener(opener)

site = SharePointSite(site_url, opener)

salesList = site.lists['Sales Distribution']

fileList = salesList.get_rows(folder='/sites/publishing/sales/Sales_Distribution/Data')

print "================================="

url = fileList[5].as_dict()['EncodedAbsUrl']
file = fileList[5].open()

content = urllib2.urlopen(url)
print content.read()