Rest connection to api; convert html/xml to json

I’m trying to connect to a train-timetable api; https://luasforecasts.rpa.ie/xml/get.ashx?action=forecast&stop=che&encrypt=false which is returning sort-of xml (there is no lise at the top saying “<?xml version="1.0" encoding="UTF-8"?>” and it not returned as “application/xml” in the http header.

The xml looks like:
<stopInfo created="2024-04-21T20:17:23" stop="Cherrywood" stopAbv="CHE"><message>Green Line services operating normally</message><direction name="Inbound"><tram dueMins="2" destination="Broombridge" /><tram dueMins="13" destination="Broombridge" /></direction><direction name="Outbound"><tram dueMins="14" destination="Bride's Glen" /></direction></stopInfo>

When I try to create a rest connection it doesn’t see this as XML so won’t convert to json (i.e. my value_json is blank) but does fill value - but value is limited to 255 characters so i don’t get the whole message.

I’ve added some regex to get these values… but it is getting messy.

Is there a way to force the xml into json? I can make valid xml using {{ ('<?xml version="1.0" encoding="utf-8"?>\n' + (value)) }}

my configuration.yaml

rest:
  - resource_template: "https://luasforecasts.rpa.ie/xml/get.ashx?action=forecast&stop=che&encrypt=false"
    scan_interval: 30000
    sensor:
      - name: "luas xml"
        value_template: {{ value_json }}
      - name: "luas message"
        value_template: >
          {{ value|regex_replace(find='.*<message>', replace='', ignorecase=False)|regex_replace(find='<\/message>.*', replace='', ignorecase=False) }}
      - name: "luas inbound"
        value_template: >
          {{ value|regex_replace(find='<direction name="Outbound".*', replace='', ignorecase=False)|regex_findall(find='<tram [\w=" \']*\/>', ignorecase=False) }}

Secondly, if i want to refresh this I can run an automation that calls the service RESTful: Reload can this be tailored so it only calls a specific rest api?

I don’t believe so, no. The conversion attempt is only made if the Content-type header is one of:

XML_MIME_TYPES = (
    "application/rss+xml",
    "application/xhtml+xml",
    "application/xml",
    "text/xml",
)

from line 30 (at time of writing) of this file, referred from lines 72ff of this file.

Your URL stubbornly returns text/html even if you send it one of the types above in the Accept header.

Call the homeassistant.update_entity service with any one of the sensors here listed as the target.

1 Like