Sending JSON request with Python

Even though this doesnt exactly answer OPs question, it should be mentioned here that requests module has a json option that can be used like this:

import requests

requests.post(
    'http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx',
    json={"temperature": "24.3"}
)

which would be equivalent to the curl:

curl 'http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx' \
    -H 'Content-Type: application/json' \
    --data-binary '{"temperature":"24.3"}'


Instead of using urllib2, you can use requests. This new python lib is really well written and it's easier and more intuitive to use.

To send your json data you can use something like the following code:

import json
import requests
data = {'temperature':'24.3'}
data_json = json.dumps(data)
payload = {'json_payload': data_json, 'apikey': 'YOUR_API_KEY_HERE'}
r = requests.get('http://myserver/emoncms2/api/post', data=payload)

You can then inspect r to obtain an http status code, content, etc

Tags:

Python

Json