Home Assistant Python API
Project description
hassapi — Home Assistant Python API Client
A Python client for the Home Assistant REST API and WebSocket API.
Installation
pip install hassapi
Quick Start
from hassapi import Hass
hass = Hass(hassurl="http://192.168.1.10:8123", token="YOUR_LONG_LIVED_TOKEN")
# Control devices
hass.turn_on("light.living_room")
hass.turn_off("switch.coffee_machine")
hass.toggle("light.bedroom")
# Read state
state = hass.get_state("sensor.temperature")
print(state.state) # e.g. "21.5"
print(state.attributes) # dict of entity attributes
print(state.last_changed) # datetime
# Run a script
hass.run_script("good_morning")
Configuration
Constructor arguments
hass = Hass(
hassurl="http://IP_ADDRESS:8123",
token="YOUR_HASS_TOKEN",
verify=True, # Set to False to skip TLS certificate verification (e.g. self-signed certs)
timeout=3, # Request timeout in seconds
)
Environment variables
If hassurl or token are not passed, the client reads from environment variables:
export HASS_URL=http://192.168.1.10:8123
export HASS_TOKEN=your_long_lived_token
hass = Hass() # reads from env
API Reference
States
# Get the state of a single entity
state: State = hass.get_state("light.living_room")
# Get states of all entities
states: StateList = hass.get_states()
# Set state and optionally attributes of an entity
state: State = hass.set_state("sensor.my_sensor", state="42", attributes={"unit": "°C"})
State object fields:
| Field | Type | Description |
|---|---|---|
entity_id |
str |
Entity identifier |
state |
str |
Current state value |
attributes |
dict |
Entity attributes |
last_changed |
datetime |
When state last changed |
last_updated |
datetime |
When state was last updated |
context |
Context |
Context (id, parent_id, user_id) |
Services
# Call any service
hass.call_service("turn_on", entity_id="light.living_room", brightness=200)
# Convenience methods
hass.turn_on("light.living_room")
hass.turn_off("switch.fan")
hass.toggle("light.bedroom")
# Covers
hass.open_cover("cover.garage")
hass.close_cover("cover.garage")
hass.set_cover_position("cover.garage", position=50)
# Input entities
hass.select_option("input_select.mode", option="Away")
hass.set_value("input_number.brightness", value=75)
# Scripts and shell commands
hass.run_script("good_morning")
hass.run_shell_command("backup")
# List all available services
services: ServiceList = hass.get_services()
Events
# List all registered event listeners
events: EventList = hass.get_events()
# Fire an event
hass.fire_event("MY_CUSTOM_EVENT")
hass.fire_event("MY_CUSTOM_EVENT", event_data={"key": "value"})
Real-time events (WebSocket)
Subscriptions are non-blocking — they start a background thread and return immediately.
import time
def on_change(event):
data = event["data"]
print(data["entity_id"], data["old_state"]["state"], "->", data["new_state"]["state"])
# Watch a specific entity for state changes
hass.subscribe_to_state_changes(on_change, entity_id="light.living_room")
# Watch all state changes
hass.subscribe_to_state_changes(on_change)
# Watch a specific event type
hass.subscribe_to_events(on_change, event_type="call_service")
# Watch all events
hass.subscribe_to_events(on_change)
# Keep the main thread alive while listening
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
hass.unsubscribe()
The client reconnects automatically on dropped connections using exponential backoff, and gives up after 5 consecutive failures.
Templates
# Render a Jinja2 template
result: str = hass.render_template("{{ states('sensor.temperature') }}")
Getting a Long-Lived Access Token
- Open Home Assistant in your browser
- Go to your profile: Settings → Your profile → Security
- Scroll to Long-lived access tokens and create one
Contributing
# Install dev dependencies and run all checks
pip install tox
tox
Individual environments:
tox -e pytest # run tests
tox -e flake8 # lint
tox -e mypy # type check
tox -e format # auto-format code
tox -e format-check # check formatting without modifying
License
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file hassapi-0.3.0.tar.gz.
File metadata
- Download URL: hassapi-0.3.0.tar.gz
- Upload date:
- Size: 13.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
27aab84c036014bc95a02db5b0cc41b7cf5b35d16b406a8b5f0c2294b29dcef5
|
|
| MD5 |
38eeb30acf8c6e5c3bcacf23adea9e28
|
|
| BLAKE2b-256 |
4feb9865d286c083abce3e2e4b1be68fce893b2af39bed954e925c568e25c033
|
File details
Details for the file hassapi-0.3.0-py3-none-any.whl.
File metadata
- Download URL: hassapi-0.3.0-py3-none-any.whl
- Upload date:
- Size: 15.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9aeb4e63f175dda703bb488cfe5a90ac3ff8a6015e6570bd31a56e86b22124cf
|
|
| MD5 |
1baf35530ca703316d2d7e9376e17612
|
|
| BLAKE2b-256 |
5400477dc8f60e3c2f4143c889dbed2774f151031635a3e3165e620cd7f7b4dd
|