I tried this sample code for my org (for which my AD admin gave full access in SharePoint :
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
site_url = "https://myname.sharepoint.com"
client_id = "xxx-xxx-xxx-xxx-xxx"
client_secret = "xxxxxxxx"
ctx = ClientContext(site_url).with_credentials(ClientCredential(client_id, client_secret))
folder_path = 'sites/SOF'
root_folder = ctx.web.get_folder_by_server_relative_path(folder_path).expand(["Files"]).get().execute_query()
print("root_folder = ", root_folder)
for file in root_folder.files:
print(file.name)
But I still get
File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://myname.sharepoint.com/_api/Web/getFolderByServerRelativePath(DecodedUrl='sites%2FSOF')?$expand=Files
I even tried site_url = "https://myname.sharepoint.com/sites/SOF"
but still it returned :
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://myname.sharepoint.com/sites/SOF/_api/Web/getFolderByServerRelativePath(DecodedUrl='')?$expand=Files
Update : entering this in my browser returns the proper XML with all the data :
So what more permissions do I need from my admin ? My client_id and client_secret are correct.
I created an Azure AD Application:
Now when I tried the code, I got the same error as below:
The 403 error
usually occurs if the application doesn't have sufficient permissions to perform the action.
To resolve the error, make sure to set up an app-only principal with tenant permissions like below:
https://xxx.sharepoint.com/_layouts/15/appinv.aspx
https://xxx-admin.sharepoint.com/_layouts/15/appinv.aspx
I used https://xxx-admin.sharepoint.com/_layouts/15/appinv.aspx
to grant permissions:
And here enter the ClientID, domain and redirect URL of the application.
For App's permission, paste the below XML and create:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>
Now click on Trust it
to grant the permissions:
I uploaded samples files in the SharePoint site:
Now, after granting the permissions I am able to print the files successfully like below:
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
site_url = "https://xxx.sharepoint.com/sites/testruk"
client_id = "ClientID"
client_secret = "ClientSecret"
ctx = ClientContext(site_url).with_credentials(ClientCredential(client_id, client_secret))
folder_path = 'doc1/folder1'
root_folder = ctx.web.get_folder_by_server_relative_path(folder_path).expand(["Files"]).get().execute_query()
print("root_folder = ", root_folder)
for file in root_folder.files:
print(file.name)
Reference: