Python script to get data from HA's REST API

Hi,
I am trying to write a python script that fetches data from Home Assistant’s REST API. I have tried to follow the instruction at REST API | Home Assistant Developer Docs.

Here is my code:

import requests

url = "http://192.168.1.4:8123/api/template"
headers = {
    "Authorization": "Bearer *my_token_here*",
    "content-type": "application/json",
    "template":"{{ states('alarm_control_panel.home_alarm') }}"
}

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

But I get the following error:

{"message":"Error rendering template: Expecting value: line 1 column 1 (char 0)"}

What am I doing wrong?
Thanks!

The template doesn’t go in headers, it goes in the postbody. The body of the request should be this for your test:

{
  "template": "{{ states('alarm_control_panel.home_alarm') }}"
}

Hi!

I’m trying to send data from a sensor connected to a Raspberry Pi to HA. I know that using an ESP32 and ESPhome would be easier, but this RPi is already there doing other stuff and has the sensor in question…

To get started, I tried switiching a light on and off:

from requests import post

url = "http://192.123.123.123:8123/api/services/switch/toggle"
headers = {
    "Authorization": "Authorization: Bearer ...",
    "content-type": "application/json",
}

data = '{"entity_id": "switch.feather_esp32v2_latching_relay"}'

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

The REST API calls work using the Flic app, so I’m pretty sure that I have all that correct. The response I get, however, is “401 Unauthorized”. Not sure what I’m doing wrong.

Assuming someone can point me in the right direction regarding the Unauthorized issue, how would I go about writing a number into an entitie’s state (in this case it’s a lux value)?

Best regards,
Andrew

… in case someone else stumbles upon this, I got it to work with the following python code:

import requests

url = "http://192.123.123.123:8123/api/services/switch/toggle"
headers = {
    "Authorization": "Bearer LOOOONGKEEEEY
}

data = '{"entity_id": "switch.feather_esp32v2_relay_latching_relay_2_switch"}'

response = requests.request("POST", url, headers=headers, data=data)

print(response.text)

It’s subtly different to the previous code - not sure exactly why the first example (which I found in the REST API docs) didn’t work.