Rest sensor - Dynamic Bearer Token (Using Sensor)

So actually found a workaround by not using secrets.
The issue is the token bearer is being refresh every time the home assistant starts, and when running the query to get the prices, the “!secret api_key_bearer_static” is equals to “unknown”

My solution is:

  1. Create helpers as input text where you will store your API key (static) and you bearer key (dynamic) and in my case some static authentication header
  2. Store your bearer token from the API in a sensor
  3. Create an automation that every time the bearer token sensor change value, change the helper text

The new API calls will look like this now:

Getting my bearer token

rest:
 - resource: "https://YOURAPI.com/"
    scan_interval: 36000 #10h
    timeout: 60
    method: "GET"
    headers:
      Authorization: "{{ states('input_text.api_auth_header') }}"
    sensor:  
      - name: "API Access Token Bearer"
        value_template: "Bearer {{ value_json['access_token'] }}"

Getting my price using the bearer token

rest:
   - resource: "https://YOURAPI.com/"
    scan_interval: 3600 #1h
    timeout: 60
    method: "POST"
    headers:
      Authorization: "{{ states('input_text.api_token_bearer') }}"
      Content-Type: "application/json"
      apikey: "{{ states('input_text.api_key') }}"
   sensor:  
      - name: "Sensor"
        value_template: "{{ value_json.prices }}"

The automation will be

alias: Update Token Bearer 
description: "" 
trigger:
  - platform: state 
    entity id:
      - sensor.api_access_token_bearer 
condition: [] 
action:
  - service: input_text.set_value
    data template:
      entity_id: input_text.api_token_bearer 
      value: "{{ trigger.to state.state }}"
mode: single
4 Likes