1. Create a token
Profile (click your user name) → Security → Long-lived access tokens → Create. It's shown once; store it like a password. Create one token per script or device so you can revoke them individually.
2. REST API
Every call needs Authorization: Bearer TOKEN.
HA=http://homeassistant.local:8123
TOKEN=YOUR_LONG_LIVED_TOKEN
# Read a state
curl -s -H "Authorization: Bearer $TOKEN" "$HA/api/states/sensor.outdoor_temp"
# Call an action (service)
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"entity_id": "light.hallway"}' "$HA/api/services/light/turn_on"
The REST API is there when the api integration is loaded. Setups using the default frontend have it; a minimal YAML setup without the frontend needs api: added.
3. WebSocket API, for live events
Polling /api/states every second is wasteful. Subscribe instead:
- Connect to
ws://HOST:8123/api/websocket. - Server sends
auth_required→ send{"type": "auth", "access_token": "TOKEN"}→ server repliesauth_ok(orauth_invalid). - Send
{"id": 1, "type": "subscribe_events", "event_type": "state_changed"}and read the event stream. Each message carries yourid.
4. Secrets in YAML
# configuration.yaml
rest_command:
notify_gateway:
url: http://192.168.1.50/notify
password: !secret gateway_password
# secrets.yaml (same config directory)
gateway_password: "YOUR_PASSWORD"
!secret keeps passwords out of files you share or post. It is not access control: a secret used in an automation is visible to admins in the YAML view and in traces. Anyone with access to the config directory or a backup can read secrets.yaml.