How to enable the Home Assistant REST API
Jun 02, 2024
382 words | 2 minutes

The Home Assistant REST API allows interatction through http(s) requests in order to change settings and get states of entities and devices on your home network, authenticated through the use of API tokens. This is extremely useful when automating home assistant through code or linking to third-party applications and services such as IFTTT.

Checking for the Home Assistant API

On almost all installations, the Home Assistant API is already enabled. If you use the Home Assistant web frontend, the API is already enabled, as the included frontend uses the Home Assistant under the hood. Another way to test if the API is enabled is by appending /api/ to your Home Assistant base URL. If you get a 401: Unauthorized error displayed in your browser, congrats, your Home Assistant API is active!

Enabling the Home Assistant API

If you are not using the Home Assistant web frontend, and the /api/ endpoint does not return 401: Unauthorized, the following steps can be taken to enable the REST API:

  1. Install the File editor Home Assistant add-on. (This can be found in Settings > Add-ons > Add-on Store > File editor)
  2. Open the File editor web UI
  3. Navigate to your configuration.yaml file within the File editor UI
  4. Add api: to the bottom of your configuration.yaml file, no extra fields required.
  5. Navigate to your Developer tools tab and hit "Check Configuration". Ensure a message appears in green saying "Configuration will not prevent Home Assistant from starting".
  6. Finally, restart your Home Assistant instance. Check if the API is enabled by appending /api/ to the end of your Home Assistant base URL.

Applications of the Home Assistant API

The Home Assistant API can be used for many personal projects, including custom displays or control panels.

For example, in python, this could be done with a simple requests call:

import requests

# Your Home Assistant instance URL and API token
url = "https://your-home-assistant:8123/api/states/light.your_light"
headers = {
    "Authorization": "Bearer YOUR_LONG_LIVED_ACCESS_TOKEN",
    "Content-Type": "application/json",
}

# Get the state of the light
response = requests.get(url, headers=headers)
light_state = response.json()
print(light_state)

# Turn on the light
turn_on_url = "https://your-home-assistant:8123/api/services/light/turn_on"
data = {"entity_id": "light.your_light"}
response = requests.post(turn_on_url, headers=headers, json=data)
print(response.status_code)

I have also used the Home Assistant API to create an app for the Fitbit sense in order to control entities at a glance. The app is available on the Fitbit app gallery, with source code and issues on GitHub