Description
I have a problem downloading a testing text file from Sharepoint in a private company behind firewall using SSO auth.
I can view and download the file manually from a web browser using the link below:
https://myfirm.sharepoint.com/sites/mysite/Shared Documents/test.txt
However, I am getting the error below when I ran the code below:
Exception has occurred: ClientRequestException
('-2130575338, Microsoft.SharePoint.SPException', 'The file /sites/mysite/Shared Documents/test.txt does not exist.', "404 Client Error: Not Found for url: https://myfirm.sharepoint.com/sites/mysite/_api/Web/getFileByServerRelativePath(DecodedUrl='%2Fsites%2Fmysite%2FShared%20Documents%2Ftest.txt')?$select=ServerRelativePath,Id")
Please note if ?$select=ServerRelativePath,Id in the error above was removed, the link below can be opened manually in a web browser without error.
https://myfirm.sharepoint.com/sites/mysite/_api/Web/getFileByServerRelativePath(DecodedUrl='%2Fsites%2Fmysite%2FShared%20Documents%2Ftest.txt')
The code below are two parts that both come from this github:
Part 1 below is working
https://github.com/vgrem/Office365-REST-Python-Client/blob/master/examples/sharepoint/auth_interactive.py
Part 2 below is NOT working with combining with part 1
https://github.com/vgrem/Office365-REST-Python-Client/blob/master/examples/sharepoint/files/download.py
test_tenant = 'myfirm.onmicrosoft.com'
test_site_url = 'https://myfirm.sharepoint.com/sites/mysite'
test_client_id = 'xxxx-xxxx-xxxx-xxxx-xxxx'
file_url = "/sites/mysite/Shared Documents/test.txt"
# below is also not working
# file_url = "Shared Documents/test.txt"
ctx = ClientContext(test_site_url).with_interactive(test_tenant, test_client_id) # this works
download_path = os.path.join(tempfile.mkdtemp(), os.path.basename(file_url))
print(download_path)
with open(download_path, "wb") as local_file:
file = (
ctx.web.get_file_by_server_relative_path(file_url)
.download(local_file)
.execute_query() # throws an error here
)
print("[Ok] file has been downloaded into: {0}".format(download_path))
Azure Setup:
The SSO is enabled for the Sharepoint, and using user name and password is disabled.
Registering the Azure app
1 In the Authentication section, create a platform configuration for Mobile and desktop applications (not Web applications!). Assuming that your notebook runs on your local machine, add http://localhost to the redirect URIs.
2 In the API permissions section, add a permission (not the second permission) from the Microsoft Graph API: User.Read
https://poznyakovskiy.medium.com/getting-data-from-a-sharepoint-hosted-excel-file-in-python-dd4e8bb723d5