I'm working on a python script that will communicate with the API of a CRM system I'm deploying right now. I can get data from the CRM server, but I can't seem to add (write) a new entry. I suspect I'm doing something silly because I'm fairly new to Python and programming in general, can someone point me in the right direction? The server does not reject the data, but it acts as if I was requesting data from /api/v1.0/payments as opposed to posting new data.
from urllib.request import Request, urlopen
headers = {
'Content-Type': 'application/json',
'X-Auth-App-Key': '[API key]'
}
values = b"""
{
"clientId": 104,
"method": 3,
"checkNumber": "",
"createdDate": "2016-09-12T00:00:00+0000",
"amount": 40,
"note": "",
}
"""
request = Request('http://[SERVER_URL]/api/v1.0/payments', data=values, headers=headers)
response_body = urlopen(request).read()
print(response_body)
I'm working based on example code from the API documentation here: http://docs.ucrm.apiary.io/#reference/payments/payments/post
Am I using urlopen correctly at the bottom?
This question/answer may be your issue. Basically your POST request is being redirected to /api/v1.0/payments/ (note the trailing slash), when that happens your POST is redirected to a GET request, which is why the server is responding as if you were trying to retrieve all of the payments info.
Other things to note are your json data is actually invalid as it contains a trailing ,
after the 'note' value, so that may be an issue issue too. I think you may also be missing the Content-Length
header in your headers. I'd recommend using the json
module to create your json data:
values = json.dumps({
"clientId": 104,
"method": 3,
"checkNumber": "",
"createdDate": "2016-09-12T00:00:00+0000",
"amount": 40,
"note": ""
})
headers = {
'Content-Type': 'application/json',
'Content-Length': len(values),
'X-Auth-App-Key': '[API key]'
}
request = Request('http://[SERVER_URL]/api/v1.0/payments/', data=values, headers=headers)