Click here to Skip to main content
15,881,639 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

I am trying to download csv file from teams sharepoint link. I am using python 3.9.
I am able to access and download file using browser and I have permission to create folder in sharepoint.

When I am trying to download file it throws error 403 forbidden. Code:
import argparse
import urllib.parse
import os
import requests
from requests.auth import HTTPBasicAuth

auth = HTTPBasicAuth('username', 'password')
headers = {'accept': 'application/json;odata=verbose'}

def download_file(filename):
   filename = filename.strip('/')
    print('Downloading\t'+filename)
    r = requests.get('https://xxx.sharepoint.com/'+"_api/Web/GetFileByServerRelativeUrl('/Shared Documents/Folderunderdocument/"+'filename.csv'+"')/$value", auth=auth, stream=True)
    with open(filename, 'wb+') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk:
                f.write(chunk)
                f.flush()

if __name__ == '__main__':
      download_file('filename.csv')


What I have tried:

Tried different python libraries
SharePy, Shareplum etc ..
Posted
Comments
Richard MacCutchan 31-May-21 5:02am    
The 403 status is returned from the server. You cannot circumvent that through code.
RAHUL(10217975) 31-May-21 5:15am    
okay, I have access to that file and I can create folder too. Not sure why 403 error wile trying from Python.
Any suggestions would be great, thanks!
Richard MacCutchan 31-May-21 5:30am    
Read again what I said. This is a server issue, and the server is telling you that your request is not allowed. So you need to talk to the owners of the server to find out why. Most likely it is because the server does not make files available for direct access. The only way you can get them is by clicking some download control on the server web pages, which then gets the file's content from the server and passes it to the browser.
Stephen Hilton 2022 22-Mar-22 18:59pm    
Just curious, did you ever find a work-around? I understand server-side constraint, but I hit a similar roadblock... I can access via browser fine, but cannot access directly via Python. Perhaps there's a work-around emulating a browser? Not a hard-blocker for me (I can cheat using OneDrive) but was curious if some creative solution popped up. Thx!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900