I am trying to post data to a SharePoint 2013 REST API using Python. I am able to successfully acquire the required X-RequestDigest
using the method from this post.
I have already tried solutions from here and here.
I can extract the required token every time, but I get this response from the server when I try to use it:
<?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<m:code>-1, System.Collections.Generic.KeyNotFoundException</m:code>
<m:message xml:lang="en-US">The given key was not present in the dictionary.</m:message>
<m:innererror><m:message>The given key was not present in the dictionary.</m:message>
<m:type>System.Collections.Generic.KeyNotFoundException</m:type>
<m:stacktrace>
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at Microsoft.SharePoint.Client.Rest.RestRequestProcessor.ReadRequestODataObject(ServerStub serverStub, Object entity)
at Microsoft.SharePoint.Client.Rest.RestRequestProcessor.InvokeMethodWithRequestODataEntry(Object target, ServerStub serverStub, String methodName)
at Microsoft.SharePoint.Client.Rest.RestRequestProcessor.TryAddEntity(Object entity, ServerStub serverStub, Object& newEntity)
at Microsoft.SharePoint.Client.Rest.RestRequestProcessor.Process()
at Microsoft.SharePoint.Client.Rest.RestRequestProcessor.ProcessRequest()
at Microsoft.SharePoint.Client.Rest.RestService.ProcessQuery(Stream inputStream, IList`1 pendingDisposableContainer)</m:stacktrace></m:innererror></m:error>
I use the following code:
# First, get security token
token_url = "https://example.com/_api/contextinfo"
tr = requests.post(token_url, auth=HttpNtlmAuth(creds[0], creds[1]),verify=False)
tokenRoot = ElementTree.fromstring(tr.content)
# Since the namespace will not be parsed, it is hardcoded into the string
token = tokenRoot.find("{http://schemas.microsoft.com/ado/2007/08/dataservices}FormDigestValue").text
print(token)
headers = {'X-RequestDigest': token}
post_url = "https://example.com/_api/web/lists/getbyTitle('listname')/items"
payload = {'__metadata': {'type': 'SP.Data.ListName'},'Title': 'test', 'date_observation': '2015-08-10T22:00:00Z'}
r = requests.post(post_url, data=json.dumps(payload), auth=HttpNtlmAuth(creds[0], creds[1]), headers = headers, verify=False)
print(r.status_code)
Any ideas whatsoever?