I’m certainly no expert either. I haven’t tried this sort of complexity. I just noted this from the esphome docs:
data_template ( Optional , mapping): Optional template data to pass along with the service call. This is evaluated on the Home Assistant side with Home Assistant’s templating engine.
From here: Native API Component — ESPHome
As it says it is evaluated on the HA side I formatted the template as I would do if using a template in HA.