How to use rest sensor (not RESTfull) with value_template

I have a rest sensor (see RESTful - Home Assistant). Note that this is not the same as RESTful Sensor - Home Assistant!

The JSON data is returned with a unit (eg. 2936 MW), which I want to remove so I can use it in a graph:

According to the docs (RESTful - Home Assistant) I can use any RESTfull config option in a sensor, how ever I can’t figure out how to use value_template (RESTful Sensor - Home Assistant).

As a workaround I added separate template sensors:

rest:
  # Swissgrid
  # Use the templated sensors swissgrid_import_none, resp. their friendly name swissgrid_import_XX
  - resource: https://www.swissgrid.ch/bin/services/apicache?path=/content/swissgrid/de/home/operation/grid-data/current-data/jcr:content/parsys/livedatawidget_copy
    sensor:
    - name: swissgrid_raw_meta0
      json_attributes_path: $.data.table[0]
      value_template: "OK"
      json_attributes:
      - label

template:
  - name: swissgrid_import
    state: "{{ state_attr('sensor.swissgrid_raw_meta0', 'label').split(' ')[2] | int }}"
    unit_of_measurement: "MW"  

How ever there should be a way to do this directly in the rest sensor, right?

Sure, don’t pick up the value as an attribute, use it as the state:

rest:
  # Swissgrid
  # Use the templated sensors swissgrid_import_none, resp. their friendly name swissgrid_import_XX
  - resource: https://www.swissgrid.ch/bin/services/apicache?path=/content/swissgrid/de/home/operation/grid-data/current-data/jcr:content/parsys/livedatawidget_copy
    sensor:
    - name: swissgrid_raw_meta0 # you might want to change this to something nicer for the frontend, like 'Swissgrid Power'. The entity id generated from this will be, sensor.swissgrid_power
      value_template: "{{ value_json.data.table[0]label.replace(' MW', '') }}"
      unit_of_measurement: "MW"  
      state_class: measurement
      device_class: power # might have to change your unit to kW or W for this option (don't forget multiply the template result too). 

The state_class is only required if you want to use long term statistics. The device_class just changes the appearance (icon). If you want to use the MW unit, just add your own icon: ... instead of this.

2 Likes

Thank you very much!

1 Like