RESTful Sensor - what if it fails?

I hoped to get feedback if the source is not available, but even force_update just updates the last read value, even if the page throws a 404 or the value is not on the site.

How can I intercept such cases? I need to be sure that the data is recent.

If the call fails, value_json wonā€™t be available to parse in the templates ā€” at least, thatā€™s my experience. So, you can check if value_json is defined.

  sensor:
    - name: SAAQIS PM Coarse
      value_template: >-
        {% if value_json %}
          {% set data = (value_json.data | last).channels | selectattr('name', '==', 'PM Coarse') | first %}
          {% if data.valid %}
            {% if data.value >= 0 %}
              {{ data.value }}
            {% else %}
              0
            {% endif %}
          {% else %}
          None
          {% endif %}
        {% else %}
        None
        {% endif %}
      unit_of_measurement: "Āµg/mĀ³"

That looks good, thank you.

Any idea, why this doesnā€™t work in my case:

Works:
value_template: "{{ value_json.NameOfVar }}"

value_template: >-
        {% if value_json %}
          {% set data = (value_json.data | last).channels | selectattr('name', '==', 'NameOfVar') | first %}
          {% if data.valid %}
            {% if data.value >= 0 %}
              {{ data.value }}
            {% else %} //I would probably remove these two lines, because I don't get negative values.
              0
            {% endif %}
          {% else %}
          None
          {% endif %}
        {% else %}
        None
        {% endif %}

It always returns None.

ERROR (MainThread) [homeassistant.helpers.template] Template variable error: No last item, sequence was empty. when rendering '{% if value_json %}

Do you have an example JSON response from that API?

Yes, it looks like this.

{ā€švar1ā€˜: true, ā€šNameOfVarā€˜: 56}

My example was specific to the JSON I get back on that API call, which is very different from yours. Nothing after if value_json can be used verbatim. I was just including that as a complete example, but without knowing your caseā€™s JSON response at the time. Sorry if I confused you.

Iā€™m going to assume you want NameOfVar as your sensorā€™s value. I have to say, that JSON looks really strange to me (not using normal ASCII quotes and the seemingly abstract key names).

Just do:

value_template: >-
  {% if value_json %}
    {{ value_json.NameOfVar }}
  {% else %}
    None
  {% endif %}

I am actually doing this ā€œfake-jsonā€ using a php script.

Thanks for your help, really helps me to get familiar wit HA.

Correction: The check should be:

value_template: >-
  {% if value_json is defined %}
1 Like

Thanks for the follow up. I will change that.