Home Assistant API Python Script

I am trying to use a Python Script to set the state of an entity in Home Assistant
Here is my code with the sensitive items disguised.

from requests import post

headers = {
    'Authorization': 'Bearer ABCDEFGHI',
    'content-type': 'application/json',
}

url = 'https://MYURL/api/config/core/check_config'

response = post(url, headers=headers)
print(response.text)

url = 'https://MYURL/api/states/fred.bloggs'

data = {
    "state": "office"
}

response = post(url, headers=headers, data=data)
print(response.text)

The response is:

{"errors": null, "result": "valid"}
{"message": "Invalid JSON specified."}

So talking to the API works, but it doesn’t like my data object.

What am I missing?

Why are you doing this when you can use the rest sensor?

My aim is to have MotionEyEOS run this script when it detects motion. So, rather than HA consuming a REST API I need it to expose an API that allows me to change the state of an entity.

Your data is a Python dictionary, not a JSON formatted string. Try:

data = '{"state": "office"}'

Or, if you need more complex data, you could define it in a Python dictionary, then use json.dumps() to convert it to a JSON formatted string:

import json

data = {
    "state": "office"
}

response = post(url, headers=headers, data=json.dumps(data))

Ah ok. Just a forewarning, if you attempt to use this with the python_script integration, you won’t be able to import anything. The environment is very restricted. You might have to move to appdaemon. Or create your own integration using your library.

EDIT: I need to read more, you said motionEye is running this script.

Of course! (beats head with heel of hand)! Thanks very much. Works a treat now.

1 Like