Reputation: 23
I am new to python programming and I have reached an impasse that I can't seem to solve. I am trying to use python requests module to to POST a request to a service in IBM Bluemix. It works fine when I use cURL to make the request but when I try to the requests module I get an error message. Since I am using the same data file, I am confused about why I am getting different results. Can anyone enlighten me?
Here is the code with access keys and URL modified as well as the what I think is the relevant part of the response: Here is the cURL:
curl -i -v -H "Content-type: application/json" -X POST \
"https://ibm.Someservice.ibmcloud.com:9999/Action/modelName?accesskey=XXXXYYYYYZZZZZ+++++etc" \
--data-binary @sample-data.json
Here is the request code:
import requests
import json
def post2ndRequest():
url = 'https://ibm.Someservice.ibmcloud.com:9999/Action/modelName?accesskey=XXXXYYYYYZZZZZ+++++etc'
files = {'file': open('sample-data.json', 'rb')}
headers = {'Content-Type':'application/json'}
r = requests.post(url, headers=headers, files=files)
print(r.text)
return r.text
temp = 'PMresponseX.txt'
F = open (temp,'wb')
F.write(post2ndRequest())
F.close()
And here is a chunk of the returned response:
<body><h1>HTTP Status 500 - org.codehaus.jackson.JsonParseException:
Unexpected character ('-' (code 45)) in numeric value: expected digit
(0-9) to follow minus sign, for valid numeric value</h1><HR size="1"
noshade="noshade"><p><b>type</b> Exception report</p><p><b>message</b>
<u>org.codehaus.jackson.JsonParseException: Unexpected character ('-'
(code 45)) in numeric value: expected digit (0-9) to follow minus
sign, for valid numeric value</u></p><b>description</b> <u>The server
encountered an internal error that prevented it from fulfilling this
request.</u></p>
It seems to be some sort of parsing error in the server yet the cURL works fine so the server side seems ok,... I have used the request module successfully before but not using https nor attaching an access key to the URL. Could that be the issue? Any help would be appreciated!
Upvotes: 2
Views: 921
Reputation: 311486
You are using the --data-binary
option to curl
, which according to the man page:
This posts data exactly as specified with no extra pro‐ cessing
whatsoever.
Whereas in your call to requests.post
you are using the files
parameter, which according to the documentation:
:param files: (optional) Dictionary of ``'name': file-like-objects``
(or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
It seems like you actually want to use the data
parameter:
:param data: (optional) Dictionary, bytes, or file-like object
to send in the body of the :class:`Request`.
Your current code is sending a multipart MIME archive where the server is expecting something completely different.
Upvotes: 1