Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending JSON request with Python

Tags:

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!

like image 654
Donal M Avatar asked Dec 26 '11 09:12

Donal M


People also ask

What is request JSON Python?

json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.

How do I send JSON data from server to client in Python?

loads() part. Send the json object as the json string and load it from the string at the TCP client. @LochanaThenuwara Send and sendall methods of socket accept string as parameter. Hence, you need to send data as string.

How do you send data in a request body in Python?

You'll want to adapt the data you send in the body of your request to the specified URL. Syntax: requests. post(url, data={key: value}, json={key: value}, headers={key:value}, args) *(data, json, headers parameters are optional.)


1 Answers

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

like image 133
simao Avatar answered Jan 24 '23 07:01

simao