Rest platform, autorization with templates

I am using rest platform to collect some data from my electric vehicle charger, via an api. I need to refresh my token every 24h, so i’ve created a own sensor to collect the token.

But i cant get it to work with the rest platform.

  - platform: rest
    resource: https://api.xxxxxxxxxxxxx/
    name: ElectricVehicleCharger
    scan_interval: 60
    value_template: '1'  #Avoid 255 err msg
    headers:
      authorization: !secret ElectricVehicleCharger_header_token
      #authorization: "{{ states_attr('sensor.ElectricVehicleCharger_token', 'accessToken' }}"

I would like to use the comment out line, but it just throws me an error. How could I solve this? thanks

"{{ state_attr('sensor.electricvehiclecharger_token', 'accesstoken' }}"
        |
        |
        ^
should be state_attr, not states_attr

Recheck the entity_id as well as the state attribute to make sure it is identical to the source you are taking the data from. (Check from Developer Tools —> States (tab) —> Search your entity)

1 Like

That was a little bummer… it should be ok now, but still gets unautorized. Checked it out in templateeditor in developer tools, and for what I can see everything looks good.

  - platform: rest
    resource: https://api.XXX
    method: POST
    name: ElectricVehicleCharger_token
    headers:
      Content-Type: application/json
    payload: '{ "grantType" : "password" , "username" : "+XXX" , "password" : "XXXX" }'
    value_template: 'OK' # dummy value, avoid 255 err msg
    json_attributes:
      - accessToken
      - refreshToken
    scan_interval: 1800

  - platform: rest
    resource: https://api.easee.cloud/api/chargers/XXXXX/state
    name: ElectricVehicleCharger
    scan_interval: 60
    value_template: 'OK'  # dummy value, avoid 255 err msg
    headers:
      #authorization: !secret xxxx
      authorization: Bearer {{ state_attr('sensor.ElectricVehicleCharger_token', 'accessToken') }}
    json_attributes:
      - smartCharging
      - cableLocked
      - chargerOpMode
      - totalPower
      - sessionEnergy
      - energyPerHour

Unfortunately, headers: do not accept templates…
There are at least 3 feature requests for this.

In the “meantime”, the workaround is to use a command_line sensor.
See, e.g:

Perfect. That was the trick to get it working. Thank you.

FWIW, I created a PR that implements template support for headers :pray:

Thats perfect. I hope it will be merged into core asap