API Call - appears to succeed but does not change state

I am just starting HA integration into a project using the REST API. First test was a simple light on which appears to work (e.g. no error response from API) however light does not turn on. On HA web it then shows icon of light as on but minus usual brightness slider and then will not change state clicking on it, I have to goto Hue to turn light on/off again for it to work again in HA.

Any ideas what I am missing?

Code…

<?php
require("include/config.php");
class HAApi {
    public $url;
    public $token;
    function __construct() {
        global $_CONFIG;
        $this->url = $_CONFIG['ha_api_url'];
        $this->token = $_ENV['HA_TOKEN'];
    }
    function curl($url,$post = false,$type = "GET") {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Authorization: Bearer '.$this->token
        ));
        $output = json_decode(curl_exec($ch),true);
        curl_close($ch);
        return $output;
    }
    function changeState($device,$state) {
        $apiURL = $this->url.'states/'.$device;
        $postRequest = array(
            'state' => $state
        );
        return $this->curl($apiURL,$postRequest,"POST");
    }
}
$ha = New HAApi;
print_r($ha->changeState("light.living_room_light","on"));

response

Array
(
    [entity_id] => light.living_room_light
    [state] => on
    [attributes] => Array
        (
        )

    [last_changed] => 2023-01-30T12:18:34.101977+00:00
    [last_updated] => 2023-01-30T12:18:34.101977+00:00
    [context] => Array
        (
            [id] => 01GR19TRFN2RM68ZCY3P50Y26Q
            [parent_id] => 
            [user_id] => 354b0fab875d41ae95cb0e29e1bb8777
        )

)

If you want to turn a light on you would use the “turn_on” service call for the “light” domain. The REST API call for service calls is a POST to:

/api/services/<domain>/<service>

Using a POST to “/api/states/<entity_id>” just changes the state and nothing else. Generally you would only do this for virtual entities you created with API calls, not real devices integrated with HA. However, I have read of people doing it with a particular motion sensor integration that gets stuck “on” (can’t remember which one).

Thank you, will go back to docs. It showed an example changing state on a light on front page of API docs so just assumed that was the call, will teach me to read more than first page :man_facepalming: