Is it possible to fetch YAML template sensor via curl?

I want to use a template sensor similar to this one: Devices via REST API - #3 by srcejon

I learned that I can fetch it on a remote machine using curl:

curl -X POST http://hassos:8123/api/template -H "Content-Type: application/json" -H "Authorization: Bearer TOKEN" \
    -d '{"template": "{% set devices = sta....  THE WHOLE TWIG CODE HERE  ....s.devices }}"}'

This works well, but as the TWIG code gets larger it becomes really ugly to read, format and maintain. I know that it’s possible to define a template sensor in a YAML file. Is it then possible to request the output (long JSON text in my case) of this YAML sensor via curl?

Maybe you can try putting the code into a file e.g test.txt and then, you can try to use -d @test.txt option.

You can try if this can be a potential solution.

Use RegEx to filter out what you exactly need?

  • Filter value | regex_findall_index(find='', index=0, ignorecase=False) will do the same as regex_findall and return the match at index.

@aceindy
I’d like to read all entities from a specific device. I think in this case this doesn’t help a lot.

@jurasjo
That file thing with @ was a good idea. I just had to copy the TWIG code and add suffix and prefix and it worked:

test.txt

{"template": "
{% set devices = states | map(attribute='entity_id') | map('device_id') | unique | reject('eq',None) | list %}
{%- set ns = namespace(devices = []) %}
{%- for device in devices %}
  {%- set entities = device_entities(device) | list %}
  {%- if entities %}
    {%- set ns.devices = ns.devices + [ entities ] %}
  {%- endif %}
{%- endfor %}
{{ ns.devices }}
"}

and then

curl -X POST http://hassos:8123/api/template \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer TOKEN" \
    -d @test.txt

Eventual variables in the original request must of course be replaced beforehand, but with sed and friends this is easy.

Thank you both for your support!