pythonsharepointazure-active-directoryoffice365api

Error retrieving sharepoint folders with Office365-REST-Python-Client


I'm working on a python project which contains a function that is supposed to retrieve a folder from the sharepoint of the company using the Office365-REST-Python-Client libary.

I already created an app and registered it to the sharepoint like in the Microsoft Doc But tbh the Microsoft documentation is quite hard to follow and leaves questions open. (Atleast for beginners)

What I have so far:

import json
import os
import sys
import traceback
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext




site_url ="https://{tenant}.sharepoint.com/sites/Colaboration"
client_id = "XXXX"
client_secret = "XXXX"


def connectAuth():
    # Initialize the client credentials
    client_credentials = ClientCredential(client_id, client_secret)

    # create client context object
    ctx = ClientContext('https://{tenant}.sharepoint.com').with_credentials(client_credentials)
    print(ctx)

    try:
        folder = ctx.web.get_folder_by_guest_url('/sites/Colaboration')
        
        ctx.load(folder)
        ctx.execute_query()
        files = folder.files
        ctx.load(files)
        ctx.execute_query()

    except Exception:
        traceback.print_exc()
        print('Problem printing out library contents')   
        #sys.exit(1)


connectAuth()

Error displayed in VSCode:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\user\Desktop\LangChain\sharepoint.py", line 51, in connectAuth
    ctx.execute_query()
  File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_runtime_context.py", line 181, in execute_query      
    self.pending_request().execute_query(qry)
  File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\office365\runtime\client_request.py", line 62, in execute_query
    raise ClientRequestException(*e.args, response=e.response)
office365.runtime.client_request_exception.ClientRequestException: ('-1, System.UriFormatException', 'Invalid URI: The format of the URI could not be determined.', '500 Server Error: Internal Server Error for url: https://{tenant}.sharepoint.com/_api/Web/GetFolderByGuestUrl')

I also couldnt find out what the App Domain & App Redirect URI is supposed to be. After 2 days of trying different solutions found on the internet I'm on my wits end.


Solution

  • I have below folders in my SharePoint document library like this:

    enter image description here

    When I ran your code in my environment to fetch folders, I got same error as below:

    import json
    import os
    import sys
    import traceback
    from office365.runtime.auth.client_credential import ClientCredential
    from office365.sharepoint.client_context import ClientContext
    
    site_url ="https://{tenant}.sharepoint.com/sites/Collaboration"
    client_id = "XXXX"
    client_secret = "XXXX"
    
    def connectAuth():
        # Initialize the client credentials
        client_credentials = ClientCredential(client_id, client_secret)
    
        # create client context object
        ctx = ClientContext('https://{tenant}.sharepoint.com').with_credentials(client_credentials)
        print(ctx)
    
        try:
            folder = ctx.web.get_folder_by_guest_url('/sites/Collaboration')
            
            ctx.load(folder)
            ctx.execute_query()
            files = folder.files
            ctx.load(files)
            ctx.execute_query()
            
        except Exception:
            traceback.print_exc()
            print('Problem printing out library contents')   
            #sys.exit(1)
            
    connectAuth()
    

    Response:

    enter image description here

    To resolve the error, I modified the code by changing to different method and got folders name successfully in response like this:

    import json
    import os
    import sys
    import traceback
    from office365.runtime.auth.client_credential import ClientCredential
    from office365.sharepoint.client_context import ClientContext
    
    site_url = "https://{tenant}.sharepoint.com/sites/Collaboration"
    client_id = "xxxxxx"
    client_secret = "xxxxx"
    
    relative_url = "/sites/Collaboration/<doclibname>"
    
    def connectAuth():
        # Initialize the client credentials
        client_credentials = ClientCredential(client_id, client_secret)
    
        # create client context object
        ctx = ClientContext(site_url).with_credentials(client_credentials)
        print(ctx)
    
        try:
            libraryRoot = ctx.web.get_folder_by_server_relative_path(relative_url)
            
            ctx.load(libraryRoot)
            ctx.execute_query()
    
            folder = libraryRoot.folders
            ctx.load(folder)
            ctx.execute_query()
    
            print("Number of folders:", len(folder))
            print("Folder names:")
            for folder_item in folder:
                ctx.load(folder_item)
                ctx.execute_query()
                print(folder_item.properties["Name"])
    
        except Exception:
            traceback.print_exc()
            print('Problem printing out library contents')   
            #sys.exit(1)
    
    connectAuth()
    

    Response:

    enter image description here