Py script service with response

I have a python script that retrieves water usage and responds with the json of the date and usage. I have this .py file added to HACs pyscript integration in the /homeassistant/pyscript/ directory and is an available service in HA.

I can see how it could be called as a new Automation but it’s unclear to me how to get the response as data available in HA. Do I need a device that calls the service? According to the doc Reference — hacs-pyscript 1.5.0 documentation, the response can be captured by the call if you set the optional keyword parameter return_response=True. But I don’t understand where this parameter would get set.

Using Home Assistant Core 2024.1.3

1 Like

@scsi050:
I have exactly the same problem and cannot find out how to get it working. I tried with return values but that does not work.

I play around with a service that does a reverse lookup for unknown phone numbers. I can pass the phonenumber and already get the name - if in the open phonebook - back. But that phone number I need to process in HA. A workaround of course would be to use a template sensor. But I would prefer to get it via return value from the service.

Have you made any progress?

Hello - Ran into this myself and finally figured it out. Pyscript documentation needs an update :sweat_smile:

So, there a couple things to do:

In your Python script file, the @service tag needs a decorator like so:

@service(supports_response="only")

This decorator has other options, which you can find here.

Next, you need to pass in “return_response=True” to the function. I decided it make it part of the function definition like so:

def convert_to_unix_timestamp(input_string, return_response=True):

Finally, your function should return a dictionary and only a dictionary. If not, you will get an error. Ex:

return { "unix_timestamp": unix_timestamp }
2 Likes

Thank you for this! Coming from Python Script to PyScript I was trying to figure this out.