How to access OH REST API from Javascript?

My setup:

Openhab 3 on Linux (Raspberry Pi OS) with Docker (Raspberry 4 with USB-SSD)

Everything (seems) to work fine. I am trying to create a rule in Javascript that adds or removes items to a certain group. The intention is to add Window/Door-items that are open for longer than x-minutes to this group to create a simple list that I can use in the sitemap for the HabAPP.

The only way for adding/removing items to a group from Javascript is to use the REST API. Testing it from the web-browser works find. But I cannot get it to work using Javascript. I am sure it is something simple that I am missing. When I try to use fetch(), XMLHttpRequest() or executeCommandLine (with curl) I always get the response

"…failed: ReferenceError: “” is not defined in

I am creating the script as part of a rule via the OH3 UI.

Am I missing a library?

Does anyone have a simple example that works for a get or put request to the OpenHAB REST API using Javascript in a rule created via the Main UI (including any library loading that might be needed)?

I really spent some time looking for an example but cannot find any complete example and did not get it to work from the bits and pieces that I found.

Thanks in advance.

You don’t need to use the REST API for this. Each Item has addGroup(groupName) and removeGroup(groupName) methods.

If you are using Rules DSL it’s as simple as

MyItem.addGroup("OpenItems")

If using one of the other languages you need to pull the Item from the ItemRegistry first

ir.getItem("MyItem").addGroup("OpenItems");

If you really want to use the REST API for this, you should use the sendHttpXRequest Actions to make the requests. But note that those API calls are protected and you’ll need to set up authentication in the headers of the requests.

Great. For now I do not need to use REST API then. I have some Shelly devices where I might want to poll power consumption using their REST API so I do not have to wait until they push updates to OH. But this is something for later. It is good to know to use sendHttpXRequest Actions when I get to it.

There is a slight mistake in your example, “addGroup” should be “addGroupName”:

ir.getItem("MyItem").addGroupName("OpenItems");

After you pointed me the right way I found this old post of yours with a lot of good information. For some reason I did not come across this before. There is also the information on “addGroupName”:

https://community.openhab.org/t/experimental-next-gen-rules-engine-documentation-4-of-writing-scripts/55963

Thanks a lot!