Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Sharepoint 2013 using Python3

I am currently trying to update a Sharepoint 2013 list.

This is the module that I am using using to accomplish that task. However, when I run the post task I receive the following error:

"b'{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"Invalid JSON. A token was not recognized in the JSON content."}}}'"

Any idea of what I am doing wrong?

def update_item(sharepoint_user, sharepoint_password, ad_domain, site_url, sharepoint_listname):
login_user = ad_domain + '\\' + sharepoint_user
auth = HttpNtlmAuth(login_user, sharepoint_password)
sharepoint_url = site_url + '/_api/web/'
sharepoint_contextinfo_url = site_url + '/_api/contextinfo'
headers = {
    'accept': 'application/json;odata=verbose',
    'content-type': 'application/json;odata=verbose',
    'odata': 'verbose',
    'X-RequestForceAuthentication': 'true'
}
r = requests.post(sharepoint_contextinfo_url, auth=auth, headers=headers, verify=False)
form_digest_value = r.json()['d']['GetContextWebInformation']['FormDigestValue']

item_id = 4991  # This id is one of the Ids returned by the code above
api_page = sharepoint_url + "lists/GetByTitle('%s')/items(%d)" % (sharepoint_listname, item_id)
update_headers = {
    "Accept": "application/json; odata=verbose",
    "Content-Type": "application/json; odata=verbose",
    "odata": "verbose",
    "X-RequestForceAuthentication": "true",
    "X-RequestDigest": form_digest_value,
    "IF-MATCH": "*",
    "X-HTTP-Method": "MERGE"

}

r = requests.post(api_page, {'__metadata': {'type': 'SP.Data.TestListItem'}, 'Title': 'TestUpdated'}, auth=auth, headers=update_headers, verify=False)
if r.status_code == 204:
    print(str('Updated'))
else:
    print(str(r.status_code))
like image 277
Francois Barnard Avatar asked Jul 15 '18 19:07

Francois Barnard


1 Answers

I used your code for my scenario and fixed the problem.

I also faced the same problem. I think the way that data passed for update is not correct

Pass like below:

json_data = {
    "__metadata": { "type": "SP.Data.TasksListItem" },
    "Title": "updated title from Python"
}

and pass json_data to requests like below:

r= requests.post(api_page, json.dumps(json_data), auth=auth, headers=update_headers, verify=False).text    

Note: I used SP.Data.TasksListItem as it is my type. Use http://SharePointurl/_api/web/lists/getbytitle('name')/ListItemEntityTypeFullName to find the type

like image 109
Karthick Raju Avatar answered Nov 09 '22 20:11

Karthick Raju