HTTP PUT from Python

Hi everybody, I’m new in using openremote platform. I’ve built an asset with different sensor entities, and now I’m trying to send data to the asset. I’ve read the /swagger/ API and I successfully send the data using a terminal with curl:
curl -i -X PUT
-H “Content-Type:application/json”
-H “Accept:application/json”
-d
‘[
{
“ref”: {
“id”: “XXX123YYY456ZZZ”,
“name”: “temperature”
},
“value”: “32”
},
{
“ref”: {
“id”: “XXX123YYY456ZZZ”,
“name”: “battery”
},
“value”: “80”
}
]’
‘https://my_site.click/api/master/asset/attributes’

Now I’m trying to make a PUT request using Python, I’ve tried in several way, but I always receive some error. This is one of the way that return a 500 Internal Error

import request
import json
url = “https://my_site.click/api/master/asset/attributes”
data = ‘{“ref”: {“id”: “XXX123YYY456ZZZ”, “name”: “temperature”},“value”: “12” }’
headers = {‘Content-type’: ‘application/json’, ‘Accept’: ‘application/json’}
r = requests.put(url, data=json.dumps(data), headers=headers)
r.status_code
500

Watching the server log file the error raised is about the deserialization of the String. Can anyone help me to explain how to use python to send data to my asset using request or socket? Also some example files are welcome. Thanks a lot,
vinz.

Hey,

I guess it would be better, if you use mqtt.
There are several examples for using mqtt with Python to publish and subscribe.

Yes, I’ve also thought to use this way, but I was hoping to make works also HTTP requests… Thank you for your advice.

You‘re welcome, just to say: http is Not the right protocol to publish/subscribe.

If you still need help, feel free to ask and questions.

Disclaimer: never used Python, not a developer… so ignore if this makes no sense:

  • I assume you have a typo at the start of your code and that ‘request’ is ‘requests’ in your actual try
  • The data you send already seems JSON format, so do you need the json.dumps?
  • Does the 12 need the “”? I should be just a number right?

You are defining data as a string and headers as object. Take a look of the post request from openremote_cli project which is written in Python and uses requests too. Especially see how payload is defined and passed to requests.post().

1 Like