It ended up being an auth issue. The admin turned off custom app authentication and it worked. Not sure if that is good practice.
Sharepoint Authentication with Python - 401 Error
My Azure admin gave me a client id and client secret by following the instructions on this page: https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs
I am using the Office365-REST-Python-Client REST API library. Here is my code:
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.client_context import ClientCredential
CLIENT_ID = "xxxxxxx-xxxxx-xxxxxxx"
CLIENT_SECRET = "yyyyyyyyyyyy/yyyyyyyyyy="
site_url = "https://companysite.sharepoint.com/"
client_credentials = ClientCredential(CLIENT_ID, CLIENT_SECRET)
ctx = ClientContext(site_url).with_credentials(client_credentials)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web title: {0}".format(web.properties['Title']))
It is producing an error at the ctx.execute_query() step:
office365.runtime.client_request_exception.ClientRequestException: (None, None, '401 Client Error: Unauthorized for url: https://companysite.sharepoint.com/_api/Web/')
Does this mean there is a problem with my authentication or with my code? I think it's an authentication issue. What are some steps we can take to fix this?
Microsoft 365 and Office SharePoint For business Windows
2 answers
Sort by: Most helpful
-
-
RaytheonXie_MSFT 40,471 Reputation points Microsoft External Staff
2023-11-02T01:37:53.5833333+00:00 Hi @Employee,
I'm glad to hear you solve the problem ,if you have any issue about SharePoint, you are welcome to raise a ticket in this forum.
By the way, since the Microsoft Q&A community has a policy that "The question author cannot accept their own answer. They can only accept answers by others." and according to the scenario introduced here: Answering your own questions on Microsoft Q&A, I would make a brief summary of this thread:
[Sharepoint Authentication with Python - 401 Error]
Issue Symptom:
”office365.runtime.client_request_exception.ClientRequestException: (None, None, '401 Client Error: Unauthorized for url:xxx“ throwed by ctx.execute_query()
Solution:
It's caused by auth issue, turned off custom app authentication by admin fixed the issue.
You could click the "Accept Answer" button for this summary to close this thread, and this can make it easier for other community member's to see the useful information when reading this thread. Thanks for your understanding!