Here's a code sample:
# Not actual payload, but exact same structure. Verified that payload is correct.
payload = {
'object': {
'token': '6867r474850557',
'contact': {
'FirstName': 'Jim',
'LastName': 'Bob',
'Email': 'email@fmail.com',
'Phone': '111-111-1111'
},
'request': {
'Subject': 'Hello!',
'Message': 'Test Message'
},
'fields': [ "LastName", "FirstName" ]
}
}
r = urllib2.Request("https://someawesomeurl.com", json.dumps(payload), {"Content-type": "application/json"})
f = urllib2.urlopen(r)
resp = f.read()
It fails on the call to urlopen with the error urllib2.HTTPError: HTTP Error 400: Bad Request
. I'm guessing I'm not sending the JSON payload properly but I'm not sure what I have to do to correct it.
EDIT Here's the working PHP implementation I'm trying to implement in Python:
$url = 'https://someawesomeurl.com';
$body = array (
'object' => array(
'token' => '6867r474850557',
'contact' => array (
'FirstName' => "Jim",
'LastName' => "Bob",
'Email' => "email@fmail.com",
'Phone' => "111-111-1111"
),
'request' => array (
'Subject' => "Hello!",
'Message' => "Test Message"
),
'fields' => array('LastName')
));
$params = json_encode($body);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_HTTPHEADER, array( "Content-type: application/json"));
$response = curl_exec($curl);
EDIT #2 Is it possible that urllib2
is modifying the JSON when sending it out? I've wrapped the urlopen
call in a try/except block and printed out HTTPError's exception message
:
[{"message":"Premature end of list at [line:1, column:727]","errorCode":"JSON_PARSER_ERROR"}]
I've run the JSON through lint and it comes back as valid so I don't know why the server would be complaining about bad formatting.