Use of template in rest sensor - payload

Hi,
I’m working on a rest sensor which does a POST request and requires a start and end date.
I read in the official docs that only a string is allowed for the payload.
is there no other way to use a template in there?

What I’m trying to achieve but doesn’t work unfortunately:

- platform: rest
  authentication: basic
  username: admin
  password: !secret mysecret
  resource_template: "https://mysite.com/v1/json_data"
  payload: >
    { 
      "startDate" : "2024-02-01",
      "endDate" : "{{ now().date() - timedelta(days=1) }}" 
    }
  method: POST
  name: "test api"
  unique_id: test_api
  value_template: 'Active'
  scan_interval: 300

this way I’m able to retrieve data from yesterday automatically, otherwise I have to change the endDate everything in the rest sensor.

Thanks

What does the response look like without dates? Can you create a template sensor from that sensor that extracts what you wish? I use a rest sensor payload like this:

payload: '{"KEYLIST": [{"CODESET": {{ codeset | int }},"CODE": {{ code | int }},"ACTION":"KEYPRESS"}]}'

Watching your single/double quotes and putting it all in a string (of JSON).

I’ve answered my own question. it’s possible to use “payload_template” instead of “payload”!
But it’s not documented on the official docs yet.

It isn’t in an official release yet. It’s in 2024.6.

1 Like

Does anyone know if “payload_template” ever made it into an official release as I can’t see it in the 2024.6 release notes?

OK, thanks. I’ve now implemented ‘payload_template’ in a POST command to a remote server but am having problems - I’m clearly missing something / making a simple mistake and would massively appreciate some assistance.

I have successfully used ‘payload_template’ with the following code (plus multiple other derivatives that all use a fixed text string like below):

payload_template: >-
{% set fr_text = '{ \"text\" : [\"' + 'A test string' + '\"], \"target_lang\" : \"EN\" }' %}
{{ fr_text }}  

… but when I substitute ‘A test string’ with the state value of a sensor the payload is no longer considered valid by the remote server.

payload_template: >-
{% set fr_text = '{ \"text\" : [\"' +  states('sensor.sourcetextsensor')  + '\"], \"target_lang\" : \"EN\" }' %}
{{ fr_text }}  

Unfortunately the remote server doesn’t provide any error response so I can’t easily debug. I have however tried using the above code (and multiple other versions) in ‘Developer Tools / Template’ and frustratingly they all appear to work fine and return exactly the same output as when using the static text.

Any ideas would be greatly appreciated.

Indent your template in relation to the yaml field it’s in.

Also you can just make a normal output and use | to_json

Apologies, that was just bad formatting when I copy / pasted the code in the post as it is already indented:

payload_template: >-
  {% set fr_text = '{ \"text\" : [\"' +  states('sensor.sourcetextsensor')  + '\"], \"target_lang\" : \"EN\" }' %}
  {{ fr_text }}

I did also try the to_json idea but again hit the same issue, here’s my code:

payload_template: >-      
  {% set fr_text = '{ \"text\" : [\"' +  states('sensor.sourcetextsensor')  + '\"], \"target_lang\" : \"EN\" }' %}
  stringified object: {{ fr_text }}
  object|to_json: {{ fr_text|to_json) }}   
payload_template: >
  {{ {'text': [states('sensor.sourcetextsensor')], 'target_lang': 'EN'} | to_json }}

Thanks for the suggestion - frustratingly I’m still hitting the same problem. To try and fault find I’ve set up a new Restful sensor pointing at a cloud echo service ‘Beeceptor’, code below:

  - resource: https://echo.free.beeceptor.com
    method: POST  
    headers:
      User-Agent: Home Assistant
      Content-Type: application/json
    payload_template: >
      {{ {'text': [states('sensor.weather_forecast_fr')], 'target_lang': 'EN'} | to_json }}
    scan_interval: 2500000
    sensor:
      - name: Translation Test 3
        unique_id: translation_test_3
        value_template: "{{ value_json.parsedBody }}"     

Using the echo service I can now see that the payload template is returning ‘unknown’ for the value of the sensor, see below:

{'text': ['unknown'], 'target_lang': 'EN'}

I’ve tried using a different text sensor, but it still returns ‘unknown’. Is it possible that payload_template isn’t actually working yet in Home Assistant?

It works, you’re using the wrong entity id then

I’ve tested the exact code above, and other variants using different entities, in the Developer Tools \ Template screen and they all return the correct values like this:

Template editor
{{ {'text': [states('sensor.weather_forecast_fr')], 'target_lang': 'EN'} | to_json }}      

Result:

Result
Result type: dict
{
  "text": [
    "DIMANCHE 8 SEPTEMBRE 2024 À 09:10"
  ],
  "target_lang": "EN"
}
This template listens for the following state changed events:

Entity: sensor.weather_forecast_fr

Yet when exactly the same template code is used as the ‘payload_template’ the result is ‘unknown’ for the sensor state. Unless I’m still missing something (which is highly possible!) the entity ID is definitely correct and so is the template code.

I’d be really interested to know if anyone has ever managed to successfully use payload_template and if so what yaml code they used. Otherwise I have to believe it doesn’t yet work.

Yes, I have. Please look in your log for errors.

I’ve checked multiple times and there’s never any log entries. The thing I don’t get is how the exact same YAML can work in the developer tools template form but when pasted into configuration.yaml it returns unknown

Turn on debugging for that integration to see the traffic

The only related debug log entries are as follows:

2024-09-19 16:27:38.203 INFO (MainThread) [homeassistant.components.sensor] Setting up rest.sensor
2024-09-19 16:27:38.204 INFO (MainThread) [homeassistant.helpers.entity_registry] Registered new sensor.rest entity: sensor.translation_test_4
2024-09-19 16:27:38.204 DEBUG (MainThread) [homeassistant.components.rest.data] Data fetched from resource: {"translations":[{"detected_source_language":"EN","text":"unknown"}]}

The sensor ‘translation_test_4’ is defined in configuration.yaml as follows:

rest:
  # Translation Service
  - resource: https://api-free.deepl.com/v2/translate
    method: POST  
    headers:
      Authorization: [redacted authorisation key]
      User-Agent: Home Assistant
      Content-Type: application/json
    payload_template: >
      {{ {'text': [states('sensor.weather_forecast_fr')], 'target_lang': 'EN'} | to_json }}
    scan_interval: 2500000
    sensor:
      - name: Translation Test 4
        unique_id: translation_test_4
        value_template: "{{ value_json }}"    

The value of sensor ‘sensor.weather_forecast_fr’ is as follows when viewed in Developer Tools / States:

Set the current state representation of an entity within Home Assistant.
If the entity belongs to a device, there will be no actual communication with that device.

Entity
sensor.weather_forecast_fr
Tip!
Press 'e' on any page to open the entity search dialogue
State
JEUDI 19 SEPTEMBRE 2024 À 10:00

is this entity also a rest entity? If yes, when you reload, that will be unknown.

Yes, it is also a rest entity. I’ve manually forced an entity update of the translation rest sensor and it now works. Thank you so much for your help, and patience!

1 Like