Using a template inside a template

I have a REST command that uses the following template for the payload in the YAML file:

payload: '{"to": "{{to}}", "data":{"title":"{{title}}","body":"{{message}}"}}'

Calling this service and setting the “to”, “title”, and “message” fields work great. However, I want to use a template to send sensor values in the message

e.g.

{
  "to": "abc", 
  "title": "CPU Temp", 
  "message":"CPU Temp is {{states('sensor.cpu_temp')}}"
}

but this doesn’t resolve the template and use the actual value of the cpu_temp sensor.

Is this even possible? Can someone help please?

Thanks.

If you are using the developer tools (call service tab) to send the data over, it won’t work. That tab is meant for debugging and it does not resolve templates.

Your code will work in a data_template field in an service call.

- service: rest_command.xxxxx
  data_template:
    to: abc
    title: CPU Temp
    message: CPU Temp is {{states('sensor.cpu_temp')}}

or

- service: rest_command.xxxxx
  data_template:{"to":"abc","title":"CPU Temp","message":"CPU Temp is {{states('sensor.cpu_temp')}}"}

Thanks @petro, but I am not able to create a new service using the yaml you provided.

I added it to my configuration.yaml (without the leading hypen) and it gives me the following error:

Integration not found: data_template
Integration not found: service

If I add the leading hyphen, I get an even longer error.

Do I add this to the configuration.yaml file or some other file?
Do I need to add this to a “services” block (although this code didn’t work)? e.g.

- services:
   - service: rest_command.xxx
      ...
      ...

In my search, I came across custom services that use python. Is this what I need to do?

Services go in scripts and automations.

Hmm… I tried this and it looks like I can use existing services in an automation/script; but what I want to do is create/define a new (custom) service with a data template as suggested by @petro.

Yes, use the code @petro posted as the action in an automation (replacing the xxxxx with the correct entity_id for the rest command)

Thanks for clarifying, I have added an automation and it’s almost there :smile:

One small issue though, my http request has a nested body an example json is as follows:

{ 
  "to": "device_id",
  "data": { "title": "CPU Temp", "message": "CPU Temp is 37.9" }
}

How do I create a data_template for this? I have tried the following but the data.title and data.message properties are not sent.

data_template:
  to: 'device_id'
  data:
    title: 'CPU Temp'
    message: "CPU Temp is {{states('sensor.cpu_temp')}}"

Any ideas? Thanks!

if this works in the service call,

then this is correct