I connect to a SharePoint site using its REST API (via Python), and things were working fine for me in SharePoint 2016. Our site admins migrated our installs to SharePoint Online, however, and the same connection call now results in a 401 Client Error: Unauthorized error.

Is there something I'm obviously doing wrong?

# Note that the old URI below was "docs/mysitename"; it is now "sites/mysitename"

root_uri = "https://mycompany.sharepoint.com/sites/mysitename"
contextinfo_uri = f"{root_uri}/_api/contextinfo"

basic_headers = {
    "Accept": "application/json; odata=verbose",
    "Content-Type": "application/json; odata=verbose",
    "odata": "verbose",
    "X-RequestForceAuthentication": "true"

auth = HttpNtlmAuth("myusername", "mypassword")

r = requests.post(contextinfo_uri, auth=auth, headers=basic_headers, verify=False)
r.raise_for_status()  # <== FAILURE HAPPENS HERE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.