Return json from Python HA service called using REST

I have set up the following:

  • Enabled the Python integration by adding “python_script:” to the configuration.yaml
  • Created the python_scripts folder under /config
  • Created a python script called hello_world.py and put it in the python_scripts folder
  • The script reads a value using data.get(“name”, “world”)
  • The script sets the output by: output = {“hello”:name}
  • The script writes a log entry: logger.error(“Hello {} at {}”.format(name, time.time()))

Contents of hello_world.py

name = data.get("name", "world")
output = {"hello":name}
logger.info("Hello {} at {}".format(name, time.time()))

I created a services.yaml file and put it in the python_scripts folder with the python script

Contents of services.yaml:

# services.yaml
python_script.hello_world:
  name: Hello World Example
  description: Testing out python services
  fields:
    name:
      description: Name to say hello to
      example: Larry

When I run the script from the “Developer tools/services” tool and pass it service data “name: Larry” I get the string “hello: Larry” in the Response section of that tool and I get a log entry “Hello Larry at…” - as expected

Result using Developer tools/services:

When I run the script by calling the rest API:

https://:8123/api/services/python_script/hello_world using the Postman tool, using HTTP POST, setting the Authorization header with my HA token and sending the body: {“name”:“Larry”}
I get a 200 response code and an empty list as a response and the log has an entry “Hello Larry at…”

CURL call I’m using:

curl --location 'https://<my ha server>:8123/api/services/python_script/hello_world' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <my ha token>' \
--data '{"name":"Larry"}'

Response:

< HTTP/1.1 200 OK
< Content-Type: application/json
< Referrer-Policy: no-referrer
< X-Content-Type-Options: nosniff
< Server:
< X-Frame-Options: SAMEORIGIN
< Content-Length: 2
< Date: Sun, 03 Mar 2024 23:12:58 GMT
<
* Connection #0 to <my ha server> left intact
[]

I was expecting to see in the response to the REST call the same or similar response as I did using the Developer tools services call.

Is it possible to return a value when calling a Python script via REST? I was expecting HA would convert the output variable into an HTTP response, serialize it as JSON maybe.

Per the doc, that API:

I guess the HA api has not been updated to support service calls with returned values.

Thanks Chris, I’ll test by updating an entity and see if I get any state changes returned. Looks like I’ll have to change my approach

Best

Larry