REST post using Python-Request
REST post using Python-Request
You need to set the content type header:
data = {data : 24.3}
data_json = json.dumps(data)
headers = {Content-type: application/json}
response = requests.post(url, data=data_json, headers=headers)
If I set url
to http://httpbin.org/post
, that server echos back to me what was posted:
>>> import json
>>> import requests
>>> import pprint
>>> url = http://httpbin.org/post
>>> data = {data : 24.3}
>>> data_json = json.dumps(data)
>>> headers = {Content-type: application/json}
>>> response = requests.post(url, data=data_json, headers=headers)
>>> pprint.pprint(response.json())
{uargs: {},
udata: u{data: 24.3},
ufiles: {},
uform: {},
uheaders: {uAccept: u*/*,
uAccept-Encoding: ugzip, deflate, compress,
uConnection: ukeep-alive,
uContent-Length: u16,
uContent-Type: uapplication/json,
uHost: uhttpbin.org,
uUser-Agent: upython-requests/1.0.3 CPython/2.6.8 Darwin/11.4.2},
ujson: {udata: u24.3},
uorigin: u109.247.40.35,
uurl: uhttp://httpbin.org/post}
>>> pprint.pprint(response.json()[json])
{udata: u24.3}
If you are using requests
version 2.4.2 or newer, you can leave the JSON encoding to the library; itll automatically set the correct Content-Type header for you too. Pass in the data to be sent as JSON into the json
keyword argument:
data = {data : 24.3}
response = requests.post(url, json=data)