Creating a Template Sensor from an API resource

Hi everyone,

I’m not sure if what I am doing is correct, but after many hours of Googling and reading examples I am somewhat stuck.

I have an API and when I type this API URL into a browser it returns me the following:

{"city":"london","date":"2020-04-21"}

I have added the following Sensor in my configuration.yaml file:

  - platform: rest
    resource: *URL*
    method: GET
    name: City_Date

When I add this to a sensor card in the lovelace UI, it brings back all the data.

What I then want to do do is split out the City and Date into individual sensors so it just returns “London” for the city and therefore I wrote the following Code.

  - platform: template
    sensors:
      City:
        friendly_name: "City"
        entity_id: sensor.City
        value_template: "{{ state_attr('sensor.City_Date', 'city') }}"

This is not returning London as my expectation.

Can someone advise please? Maybe there is an easier or simpler method of achieving my result.

1 Like

This is a RESTful Sensor whose state will be the value of the “city” key (london) and with an attribute called date which contains the value of the “date” key (2020-04-21).

  - platform: rest
    resource: *URL*
    method: GET
    name: City
    value_template: "{{value_json.city}}"
    json_attributes:
      - date
1 Like

Hi Taras,

That’s working now. But how do I get multiple pieces of data. i.e. the API has:

{“city”:“london”,“shop”:“empty”,“postcode”:“E10”,“date”:“2020-04-21”}

So “shop” key would be (empty) and “postcode” key would be (E10)

I’ve tried the following code but it only brings back the last piece of data, i.e postcode.

  • platform: rest
    resource: URL
    method: GET
    name: City
    value_template: “{{value_json.city}}”
    name: Shop
    value_template: “{{value_json.shop}}”
    name: PostCode
    value_template: “{{value_json.postcode}}”

Like this:

  - platform: rest
    resource: *URL*
    method: GET
    name: City
    value_template: "{{value_json.city}}"
    json_attributes:
      - shop
      - postcode
      - date

For more information, see the examples in the documentation: Fetch multiple JSON values and present them as attributes.

2 Likes

Thank you so much, with your help and the guide you left I was able to do exactly what I needed. I really appreciated it. :slight_smile:

1 Like