[Python] Uploading a file to SharePoint using the Office365-REST-Python-Client library

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I want to upload a file to my SharePoint site using Python. And the Office365-REST-Python-Client module is apparently the way to go. The code I am using is as follows:

    def upload_document_to_sharepoint(local_file_path, sharepoint_folder_path):
    # Authenticate with SharePoint
    credentials = ClientCredential(CLIENT_ID, CLIENT_SECRET)
    ctx = ClientContext(SHAREPOINT_SITE_URL).with_credentials(credentials)

    # Get the target folder
    target_folder = ctx.web.get_folder_by_server_relative_url(sharepoint_folder_path)

    file_name = os.path.basename(local_file_path)

    # Open the local file in binary read mode
    with open(local_file_path, 'rb') as file_content:
    uploaded_file = target_folder.files.upload(local_file_path, file_content.read()).execute_query()
    print(f"File '{file_name}' uploaded successfully to: {uploaded_file.serverRelativeUrl}")


    Which is pretty straightforward. Except it gives me the following error:


    office365.runtime.client_request_exception.ClientRequestException: ('-2147024891, System.UnauthorizedAccessException', 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))', '403 Client Error: Forbidden for url: https://<>/_api/contextInfo')
    ​

    It is completely unclear on where and how to get the right access tokens/secrets/app-ids from SharePoint/Azure.

    I created an app secret on the _layouts/15/appregnew.aspx page of my SharePoint. I can then create an app (which is completely unfindable afterwards) and using _lavouts/15/appinv.aspx I seem to be able to trust that created token.

    Still the same error occurs. And I am completely lost on what exactly I am doing here. I am used to creating AppId, Secrets and allowing access to APIs (This is one thing Google seems to do quite well). But with SharePoint I am completely lost.

    I also tried to get this working with tokens from Azure, but even after allowing everything on SharePoint, I get a 403 error (even logging in doesn't seem to work).

    So, how do I set up access to my SharePoint to upload a file using Python?

    Continue reading...

Compartilhe esta Página