Can't get rest sensor to work

Here is the config for the sensor I am trying to setup:

  - platform: rest
    resource_template: 'http://v0.postcodeapi.com.au/radius/?latitude={{ states.device_tracker.KAB.attributes.latitude }}&longitude={{ states.device_tracker.KAB.attributes.longitude }}&distance=1000'
    value_template: '{% if my_test_json.0 != null %}{{ my_test_json.0.name}}{% endif %}'
    name: kab_suburb
    headers:
      Accept: 'application/json'

I have checked the data from the web page (assuming that the lat & long is working correctly) and the response appears to be right…
However no kab_suburb sensor is being created … I have other rest sensors; but this is the first one where I have a resource_template
Any ideas as to what is going on?
Thanks in advance

Hi Kriss,

do you have sensor: above - platform ?

I see no issues with your template. Do you see any errors in the logs? Does the template render correctly when you try in Developer Tools -> Templates?

the template {{ states.device_tracker.KAB.attributes.latitude }} works for me (using my own device tracker of course). So does the whole line ie

http://v0.postcodeapi.com.au/radius/?latitude={{ states.device_tracker.KAB.attributes.latitude }}&longitude={{ states.device_tracker.KAB.attributes.longitude }}&distance=1000

However I don’t understand this bit

 my_test_json.0

Yes, it’s the same for me, I tested it as well. Just wanted to make sure that he uses the correct device tracker.

Try this:

  - platform: rest
    resource_template: 'http://v0.postcodeapi.com.au/radius.json?latitude={{ states.device_tracker.KAB.attributes.latitude }}&longitude={{ states.device_tracker.KAB.attributes.longitude }}&distance=1000'
    value_template: '{% if value_json.0 != null %}{{ value_json.0.name}}{% endif %}'
    name: kab_suburb
    headers:
      Accept: 'application/json'

I agree.

@i00

my_test_json.0

Should not work. when accessing items that are numbers inside objects getitem should be used.

my_test_json[0]

Also, the variable my_test_json should be changed to value_json, not what you used in the template editor.

Oh and I noticed that null is used. Null is not valid in jinja…

  - platform: rest
    resource_template: 'http://v0.postcodeapi.com.au/radius/?latitude={{ states.device_tracker.KAB.attributes.latitude }}&longitude={{ states.device_tracker.KAB.attributes.longitude }}&distance=1000'
    value_template: '{% if value_json[0] is defined %}{{ value_json[0].name }}{% endif %}'
    name: kab_suburb
    headers:
      Accept: 'application/json'

Still not working:

New yaml is:

  - platform: rest
    resource_template: 'http://v0.postcodeapi.com.au/radius/?latitude={{ states.device_tracker.kab_phone.attributes.latitude }}&longitude={{ states.device_tracker.kab_phone.attributes.longitude }}&distance=1000'
    value_template: '{% if value_json[0] is defined %}{{ value_json[0].name}}{% endif %}'
    name: kab_suburb
    headers:
      Accept: 'application/json'

There is an error in the log (didn’t notice it before):

Log Details (ERROR)
Wed Jan 08 2020 06:16:03 GMT+1000 (Australian Eastern Standard Time)
Error while setting up platform rest
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 222, in async_render
    return compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.7/site-packages/jinja2/asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
  File "/usr/local/lib/python3.7/site-packages/jinja2/sandbox.py", line 387, in getattr
    value = getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'None' has no attribute 'attributes'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 150, in _async_setup_platform
    await asyncio.wait_for(asyncio.shield(task), SLOW_SETUP_MAX_WAIT)
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 442, in wait_for
    return fut.result()
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/homeassistant/homeassistant/components/rest/sensor.py", line 95, in setup_platform
    resource = resource_template.render()
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 207, in render
    self.hass.loop, self.async_render, kwargs
  File "/usr/local/lib/python3.7/concurrent/futures/_base.py", line 435, in result
    return self.__get_result()
  File "/usr/local/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
  File "/usr/src/homeassistant/homeassistant/util/async_.py", line 70, in run_callback
    future.set_result(callback(*args))
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 224, in async_render
    raise TemplateError(err)
homeassistant.exceptions.TemplateError: UndefinedError: 'None' has no attribute 'attributes'

I am testing the response here:
https://reqbin.com/xps3pots
The feeding the result into the developer template editor like:

{% set value_json = [
    {
        "name": "Brisbane Adelaide Street", 
        "postcode": 4000, 
        "state": {
            "name": "Queensland", 
            "abbreviation": "QLD"
        }, 
        "locality": "BRIS CITY CNTRY", 
        "latitude": -27.465, 
        "longitude": 153.02340000000001
    }, 
    {
        "name": "Spring Hill", 
        "postcode": 4000, 
        "state": {
            "name": "Queensland", 
            "abbreviation": "QLD"
        }, 
        "locality": "BRIS CITY CNTRY", 
        "latitude": -27.465, 
        "longitude": 153.02340000000001
    }
] -%}
{% if value_json[0] is defined %}{{ value_json[0].name}}{% endif %}

Any other ideas? … Thanks again K

That error is related to device_tracker.kab_phone not existing. Is that spelled correctly? Does that entity exist?

I need to ask again, did you try your resource template in the Template Editor and get the desired result?

What is the entity_id of your device tracker? In the OP you used device_tracker.KAB, now you use device_tracker.kab_phone.

I call it kab as I don’t want to use my real phone name … but either way … when I put the resource_template into the template editor I get:

http://v0.postcodeapi.com.au/radius/?latitude=-27.0000&longitude=153.0000&distance=1000

…Also I have truncated the values as to not actually reveal my real location :slight_smile:

that cannot possibly be an entity id as they are lower case only.

I’m sorry, didn’t think of that :upside_down_face:

Yeah, I didn’t even notice this, was to focused on finding an error in the template :joy:

I guess it doesn’t matter if everyone knows my middle name :stuck_out_tongue: … so here is my full yaml:

sensor:
  - platform: rest
    resource_template: 'http://v0.postcodeapi.com.au/radius/?latitude={{ states.device_tracker.kris_alexander_bennett_phone.attributes.latitude }}&longitude={{ states.device_tracker.kris_alexander_bennett_phone.attributes.longitude }}&distance=1000'
    value_template: '{% if value_json[0] is defined %}{{ value_json[0].name}}{% endif %}'
    name: kris_alexander_bennett_suburb
    headers:
      Accept: 'application/json'
    scan_interval: 900

Like I said resource_template and the other tests I mentioned above work as I would expect…
Any ideas? Thanks

I’m assuming you’re getting startup errors. This should get round during startup by defaulting to 0,0

sensor:
  - platform: rest
    resource_template: >
      {% set lat = state_attr('device_tracker.kris_alexander_bennett_phone', 'latitude') | float %}
      {% set lon = state_attr('device_tracker.kris_alexander_bennett_phone', 'longitude') | float %}
      {{ 'http://v0.postcodeapi.com.au/radius/?latitude={}&longitude={}&distance=1000'.format(lat, lon) }}
    value_template: '{% if value_json[0] is defined %}{{ value_json[0].name}}{% endif %}'
    name: kris_alexander_bennett_suburb
    headers:
      Accept: 'application/json'
    scan_interval: 900
2 Likes

Thanks … that did it … I wish there was a way to set the initial delay like:

    scan_interval: 900
    initial_reading_delay: 60

I don’t know of a way to do that.