Python Requests not updating state

Hi there!
I want to update the state of a sensor via a python script on another machine.
So far, I have

import requests
def hassrequest(state):
    hassurl = 'http://192.168.0.89:8123/api/states/sensor.xyz_status'
    token = "Bearer [token]"
    data = {"state": state, 
    "attributes": {"unit_of_measurement": "", "friendly_name": "XYZ Status"}}
    headers = {"Authorization": token,
    "Content-Type": "application/json"}
    try:
        hassstatus = requests.post(hassurl, data=data, headers=headers ,timeout=1)
        print("RAN THE POST")
    except requests.exceptions.RequestException:
        print("EXCEPTION")
        
    print(headers)
    print(data)
    
hassrequest("TEST2")

but doesn’t seem to do anything. I can’t see any logged events in the GUI either.
The header is: {'Authorization': 'Bearer [token]', 'Content-Type': 'application/json'}
The data is {'state': 'TEST2', 'attributes': {'unit_of_measurement': '', 'friendly_name': 'XYZ Status'}}

If I run

curl -X POST 
-H "Authorization: Bearer [token]" 
-H "Content-Type: application/json"
-d '{"state": "TEST1", "attributes": {"unit_of_measurement": "", "friendly_name": "XYZ Status"}}'
http://192.168.0.89:8123/api/states/sensor.XYZ_status

then the status updates fine.

I can’t seem to find what the issue is.

Thanks!

Try using

hassstatus = requests.post(hassurl, json=data, headers=headers ,timeout=1)

I believe the data parameter is for form encoded data rather than JSON.

1 Like

Genius! Thanks!