How to handle a failed RESTful sensor API call

The REST sensor raises an error and returns an empty reply if no data is returned from the GET. This then causes an error when evaluating a template sensor.

I currently have this value_template which I think need to change to use state_attr() which I think should avoid an exception being raised.

value_template: "{{ states.sensor.octopus.attributes.results[-1].value_inc_vat|round(2) }}"

How can I do that if the results is an array?

Is there another way of avoiding the error?

Don’t have anything to test now, but have you tried:

value_template: "{{ state_attr('sensor.octopus', 'results')[-1].value_inc_vat|round(2) }}"

Thanks - obvious really, just couldn’t see it.

It passes config check so I’ll see what happens - thanks.

I gave this a shot, but unfortunately it does not have the desired effect. If the restful api call fails, sensors get no data and report erroneously. You can see the effect here: image

I abandoned this approach and wrote a Node-RED node for doing this. There are also a couple of Appdaemon solutions here as well.