Basic usage of Rest API

Hello,
I am trying to create external php script hosted by third party web hosting service that will be periodically checking if my OpenHAB is running. My intention is to check Rest API response. If there is proper response then OpenHAB is running and if not there might be a problem - maybe power outage or internet connection problems… in this case email notification will be sent to me. My OpenHAB is running on Raspberry Pi which is behind non-public IP address.
Question 1: Is this a good way to achieve this kind of notification functionality?
Question 2: If yes then how to use rest API? I have trouble to use it even with provided docs. I want to use API token for authentication which I have already created. Lets say this is my token: “oh.myfirsttoken.123”.
How do I read API responses then? I try to follow this restdocs.
For example I want to check systeminfo of my OpenHAB on this API address: https://home.myopenhab.org/rest/systeminfo
I use following shell command with my auth token but it returns “Unauthorized”:

curl -X GET --header "Accept: application/json" "https://home.myopenhab.org/rest/systeminfo" -u '{oh.myfirsttoken.123}:'

When I get it work using above bash/shell curl command then I will try to get same responses using php script.

  • Platform information:
    • Hardware: R-Pi 4B
    • OS: openhabian-pi-raspios32-v1.6.5.img.xz
    • openHAB version: 3.x

Are you getting the Unauthorized from myopehab.org are you getting it from your OH instance? That;'s the question. Remember that myopenhab.org has its own authentication separate from and in addition to the REST API authorization token.

I’m not certain how the two authorizations work with each other but you might try just accessing an Item or some other endpoint that doesn’t require authorization to access.

Spend some time looking into how authorization works with HTTP. You’ll need to pass the authorization as a HTTP header. When using username and password that needs to be Base64 encoded first. I’ve not done tokens but assume it works in a similar way. I know you can find lots of tutorials on how to do that as well.

When you execute the API call from the API Explorer built into openHAB itself (under Developer Tools) you can see the exact curl command that would be called and the result from the call. Running the systeminfo call produces the following curl command:

curl -X GET "http://argus:8080/rest/systeminfo" -H "accept: application/json" -H "Authorization: Bearer eyJra....."

Notice that argument that adds an Authorization header. It’ll be followed by a long string of random numbers and letters. In my case I’ve already authorized so that string is coming from a cookie I think. I suspect you can use the API Token in that place as well. But don’t forget that this is just the authorization for your openHAB server, not myopenhab.org which needs it’s own authorization.

It’s not how I would do it/have done it. It’s very easy to set up something msmtp on a Linux machine which will let you send emails using an external mail server (e.g. Gmail). Then you can bypass myopenhab.org entirely and just worry about connecting to OH directly. A simple cron job can then “ping” OH and send an email if it doesn’t respond.

I personally use Zabbix to monitor all of my services and network. It sends an email when ever anything goes wrong.

Sorry, I am not sure what instance means. Does the instance refer to connection to OpenHAB directly for example via local network instead of through cloud service like myopehab.org?
I am most likely trying to get API response from myopehab.org service where I have cloud connection to my OpenHAB.
My OpenHAB device is running on remote location using GSM internet conection outside my local network so I guess I have to use myopehab.org “interface”.

I have tried that before but probably using it wrong because when I copy/paste my command to my Linux terminal I also get “Unauthorized”:
Screenshot at 2021-08-30 20-16-30

Same command generates correct response in myopehab.org API explorer:

I have foud this post from you. I guess you are describing there how to authorize to get API response via myopenhab url. Is that relevant for me in order to get API response from myopenhab.org? If yes I will research that option more deeply.

myopnehab.org has it’s own authentication you have to pass before you ever get your openHAB running on your RPi. You have to get past that authentication before the auth token ever comes into play.

Right because, as I said, that particular authorization string was generated and stored in a cookie. It is a random string that authorizes that specific client to interact with the API. curl is a different client so it needs to separately authenticate and get its own cookie. Or it needs to reauthenticate on every call which is more likely going to be the case.

Look at the date on that post. That was more than three years ago, long before OH 3 and long before OH implemented any authentication on the REST API. It is not really relevant here. That shows you how to authenticate with myopenhab.org but then you’ll be blocked in your REST API call because I don’t think you can authenticate again on openHAB itself.

curl.  -> myopenhab.org ->  openHAB

Both of those arrows above have a separate authentication required and I don’t know if there is a way to supply both authentications in one curl request.

Well I am kind of lost here. I tried to get response via browser using this url: https://home.myopenhab.org/rest/systeminfo
After entering that url into browser I was asked for username and password and after I submitted it I was shown this content:
Screenshot at 2021-08-30 22-47-18

Similar outcome obtained when using Linux terminal and curl command with username and password provided in one command (instead of token):
Screenshot at 2021-08-30 22-58-30

Right.

bowser -> myopenhab,org

That’s the first authentication required. That’s the username and password that was requested.

myopenhab.org -> REST API

That’s the second authentication required. That’s where the API Token would be applied. But as you saw, it didn’t ask for a username and password because you bypassed that by calling the REST API directly. You need to research to figure out how or whether it’s even possible to achieve both authentications with one call.

Though, as I hinted t above, not all the REST API end points require authentication. Try getting the state of an Item. That shouldn’t require the second authentication.

Have you tried to do a multiple step approach:

  • just login to home.myopenhab.org
  • extract sessionid, tokens, cookies from the answer
  • then do a test ( second run ) to check if you can continue to access the content without further authentication but by reusing the before received information ( cookie, sessionid etc. )
  • once that works continue to access to the REST API by reusing the extracted information and setting additional header information like cookie resp. authentication for your OH setup

Now I understand what you have meant. And it works.
I know it is not the cleanest solution but for now is good for me :slight_smile:
First I have created an item “MyItem” that is always set to “ON” after openHAB startup.
If anybody is curious here is my working code that checks if OpenHAB is online using this dedicated item.

php:

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://home.myopenhab.org/rest/items/MyItem/state",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 15,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array("Content-type: text/plain"),
  CURLOPT_USERPWD => "myusername:mypassword"
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

//echo $response;

if($response !== "ON") {
  // there is an issue
  echo "err: (". $err."); response: (".$response.")";
  // send notification email
} else {
  // openHAB is online
  echo "ok";
}

shell:

curl -X GET "https://home.myopenhab.org/rest/items/MyItem/state" -H  "accept: text/plain" -u myusername:mypassword

thx

Switching items through myopenhab.org works for if I set the username and password using the curl -u user:password option and then use an API token that I append to the URL using /https://home.myopenhab.org/rest/items/youritem?access_token=yourtoken

This should first authenticate with myopenhab using the curl option and then with the REST api using the token.

2 Likes

@sheg0 , this works fine, however, as far as I recall URL’s are never encrypted so your token is visible for others. That might not be a direct problem, as someone need physical access to your OH-server to use it locally, or someone additionally needs the username/password from the OH-cloud.

However, there is a better possibility, use the -U option from curl to authorize a proxy. This worked for me fine to give item someItemName the value 27 :

curl -X PUT -H "content-Type: text/plain" -d 27 -U xyZYourLongToken.....567:"" -u myemail@somedomain.org:mypassword https://home.openhab.org/rest/items/someItemName/state

Note that I used double quotes at the -U option, because then you specify an empty password. If you omit these, curl asks you for a password and you can give that on the command line.

As far as I’m concerned, it would be nice to put this statement in the documentation as well. I’d be happy to do that, but I have never done that…

That is not true, all of the http traffic is encrypted. The only thing that might be visible is the hostname, if SNI is used in the TLS handshake. But since that is just home.myopnhab.org it shouldn’t be a privacy concern.

If I set curl -u xxx@xx:Password "https://home.myopenhab.org/rest/items/Hue_ambiance_candle_1_Brightness?access_token=KEY I get the error code: No such file or directory

there is nothing described, how I can interact with the myopenhab API: openHAB API tokens | openHAB