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!
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.
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.
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With