So I am trying to write a Python script that will be able to update a list item in company's SharePoint (intranet), and for some reason in the script when I do the "post request" (for updating item) it results in a 401 unauthorized error. I am using HttpNtlmAuth and I think the credential is good as there is no problem for me to do the get request and look up list items. I would like to have some helps or insights. The following is part of my codes:

# the credential
auth=HttpNtlmAuth("user", "password")
# -------------- get request --------------
# the headers for get request
headers_get = {'accept': 'application/json;odata=verbose'}
# no problem for this one
response_get = requests.get(sharepoint_url+"lists/GetByTitle('%s')" % sharepoint_listname, auth=auth, headers=headers_get)

# -------------- post request --------------

# specify the link of that item I want to update
api_page = sharepoint_url + "lists/GetByTitle('%s')/GetItemById(%d)" % (sharepoint_listname, item_id)

# the headers for post request
headers_post = {
"Content-Type":"application/json; odata=verbose",
"X-RequestForceAuthentication": "true",
"X-RequestDigest" : form_digest_value, # should be good
"IF-MATCH": etag, # should be good
"X-HTTP-Method" : "MERGE"

# data sent to update; which should be good 
# as if I modify it 400 error will occur rather than 401 any more
data = json.dumps({'__metadata': { 'type': 'ListItemEntityTypeFullName' }, 'some column': 'the updated value'})

# Here 401 error encountered
response_post = requests.post(api_page, data, auth=auth, headers=headers_post)

After doing some researches I think probably the reason is I didn't have Authorization: "Bearer " + accessToken in my headers, as in Microsoft's documentation this is included. However, I also checked other blogs and it seems this token thing doesn't matter. For example: this and this.

Any help, idea or insight would be appreciated. Thank you very much!

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.