I am trying to get multiple values from a REST API with the goldapi.io site. I’m able to return a proper value from the call, but when I configure multiple sensors using the template platform, I can’t retrieve a single value. I’ve tried anything in the book and a lot more, but that didn’t help. This is the code in my sensors.yaml:
# Gold Market Data Sensor
- platform: rest
resource: https://www.goldapi.io/api/XAU/EUR
name: "Gold API"
method: GET
value_template: >
{% if value_json.price is defined %}
{{ (value_json.price * 32.1507)|round(0)|int}}
{% elif value_json.error is defined %}
{{ 55111|int }}
{% else %}
{{ 55222|int }}
{% endif %}
scan_interval: 31536000
headers:
x-access-token: !secret gold_api_key
Content-Type: "application/json"
- platform: template
sensors:
gold_api_price:
value_template: "{{ state_attr('sensor.gold_api', 'price') }}"
gold_api_error:
value_template: "{{ state_attr('sensor.gold_api', 'error') }}"
The call returns this JSON if a valid API-key is presented:
{"timestamp":1673135572,"metal":"XAU","currency":"EUR","exchange":"FOREXCOM","symbol":"FOREXCOM:XAUEUR","prev_close_price":1741.92,"open_price":1741.92,"low_price":1740.5,"high_price":1762.11,"open_time":1672963200,"price":1752.96,"ch":11.04,"chp":0.63,"ask":1753.75,"bid":1752.17,"price_gram_24k":56.359,"price_gram_22k":51.6624,"price_gram_21k":49.3141,"price_gram_20k":46.9658,"price_gram_18k":42.2692}
… and this if an invalid key is presented:
{"error":"Invalid API Key"}
In the Template Editor I test these three values:
{{ states('sensor.gold_api') }} # Returns the proper gold price as calculated from vaue_json
{{ states('sensor.gold_api_price') }} # Returns unknown
{{ states('sensor.gold_api_error') }} # Returns unknown
Both value_json.price and value_json.error are defined and recognized by the rest value-template, but the template sensors can’t for some reason reference the other JSON values.
I’ve referenced the multi-sensor documentation of the rest-platform extensively, but I don’t see what’s going wrong here. Please help!