Donal M
Donal M

Reputation: 1315

Sending JSON request with Python

I'm new to web services and am trying to send the following JSON based request using a python script:

http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx&json={power:290.4,temperature:19.4}

If I paste the above into a browser, it works as expected. However, I am struggling to send the request from Python. The following is what I am trying:

import json
import urllib2
data = {'temperature':'24.3'}
data_json = json.dumps(data)
host = "http://myserver/emoncms2/api/post"
req = urllib2.Request(host, 'GET', data_json, {'content-type': 'application/json'})
response_stream = urllib2.urlopen(req)
json_response = response_stream.read()

How do I add the apikey data into the request?

Thank you!

Upvotes: 27

Views: 90179

Answers (3)

leberknecht
leberknecht

Reputation: 1714

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"}'

Upvotes: 7

simao
simao

Reputation: 15509

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

Upvotes: 41

Guy
Guy

Reputation: 14790

Maybe the problem is that json.dumps puts " and in the json you put in the url there are no "s. For example:

data = {'temperature':'24.3'}
print json.dumps(data)

prints:

{"temperature": "24.3"}

and not:

{temperature: 24.3}

like you put in your url.

One way of solving this (which is trouble prone) is to do:

json.dumps(data).replace('"', '')

Upvotes: 3

Related Questions