Rest sensor API question

Hi!

I’m trying to receive date via API from my garbage company and would like to have it presented in a sensor in homeassistant, like next date for the garbage truck to arrive.

I have managed to get some information with this setup:

And when i run the HTTP POST command in postman or do a curl i get this JSON output:
Is there some way to create a REST sensor in home assistant that hold the upcoming date from current day?

[
{
“containerId”: “11A”,
“date”: “2022-05-02T00:00:00”,
“title”: “Garbage pickup”
},
{
“containerId”: “12A”,
“date”: “2022-05-02T00:00:00”,
“title”: “Garbage pickup”
},
{
“containerId”: “11A”,
“date”: “2022-05-16T00:00:00”,
“title”: “Garbage pickup”
},

thanks in advance for every tip!

I believe you should try and make the JSON return an attribute instead with

json_attribute:

Just to be clear, the return is both past days and future days?

Thanks for reply.
That’s correct, the response is both holding past and upcoming dates.
So i would only like to present the nearest date from current.

I think you can use a value template like this:

value_template: >
                 {% set ns = namespace(found = '') %}
                 {% for item in json_value %}
                   {% if as_timestamp(item.date) > now().timestamp() and ns.found == '' %}
                     {{ item.date[0:10] }}
                     {% set ns.found = 'found' %}
                   {% endif %}
                  {% endfor %}

Keep in mind this will change at midnight the day of garbage pickup.

If you want to postpone the change then you can do like this:

Change as_timestamp(item.date) to as_timestamp(item.date | replace("T00", "T23")) or whatever time you want it to change.

Great it seems to work!
I receive 2022-05-30 and that’s correct date for next pickup.
Now i just wan’t to understand how it works :slight_smile:
Where can i find documentation about this?

It’s Jinja2.
You can find a link in the developer tools:
image

It loops the array (json_value).
It takes the datetime and makes it UNIX time to compare it with now, and makes sure it’s the first item that is in the future.
If it is, then it takes the first ten characters of the item.date.
Sets found to “found”. Could be anything really, it’s just to make sure the if statement becomes false (ns.found == ‘’).

And that’s about it…

Cool, will have a look at it ! And thank’s once again :slight_smile: