Code Reference
Interact with your Homeassistant Instance remotely.
- class homeassistant_api.Client(api_url, token, use_async=False, verify_ssl=True, **kwargs)
The all-in-one class to interact with Home Assistant!
- Parameters:
api_url (
str) – The location of the api endpoint. e.g.http://localhost:8123/apiRequired.token (
str) – The refresh or long lived access token to authenticate your requests. Required.global_request_kwargs – A dictionary or dict-like object of kwargs to pass to
requests.request()oraiohttp.ClientSession.request(). Optional.cache_session – A
requests_cache.CachedSessionobject to use for caching requests. Optional.async_cache_session – A
aiohttp_client_cache.CachedSessionobject to use for caching requests. Optional.
- async async_check_api_config()
Asks Home Assistant to validate its configuration file and returns true/false.
POST /api/config/core/check_config- Return type:
- async async_fire_event(event_type, **event_data)
Fires a given event_type within homeassistant. Must be an existing event_type.
POST /api/events/<event_type>- Return type:
- async async_get_components()
Returns a tuple of all registered components.
GET /api/components
- async async_get_config()
Returns the yaml configuration of homeassistant.
GET /api/config
- async async_get_domain(domain_id)
Fetches all
Service’s under a particular serviceDomain. Uses cached data fromget_domains()if available.
- async async_get_entities()
Fetches all entities from the api.
GET /api/states
- async async_get_entity(group_id=None, slug=None, entity_id=None)
Returns a Entity model for an
entity_id.GET /api/states/<entity_id>
- async async_get_entity_histories(entities=None, start_timestamp=None, end_timestamp=None, significant_changes_only=False)
Returns a generator of entity state histories from homeassistant.
GET /api/history/period/<timestamp>- Return type:
- async async_get_error_log()
Returns the server error log as a string.
GET /api/error_log- Return type:
- async async_get_event(name)
Gets the
Eventwith the specified name if it has at least one listener. Uses cached data fromget_events()if available.
- async async_get_events()
Gets the Events that happen within homeassistant
GET /api/events
- async async_get_logbook_entries(*args, **kwargs)
Returns a list of logbook entries from homeassistant.
GET /api/logbook/<timestamp>- Return type:
- async async_get_rendered_template(template)
Renders a given Jinja2 template string with Home Assistant context data.
POST /api/template- Return type:
- async async_get_state(*, entity_id=None, group_id=None, slug=None)
Fetches the state of the entity specified.
GET /api/states/<entity_id>- Return type:
- async async_get_states()
Gets the states of all entities within homeassistant.
GET /api/states
- async async_request(path, *, params='', method='GET', headers=None, **kwargs)
Base method for making requests to the api
- Return type:
- async static async_response_logic(response)
Processes custom mimetype content asyncronously.
- Return type:
- async async_set_state(state)
This method sets the representation of a device within Home Assistant and will not communicate with the actual device. To communicate with the device, use
Service.trigger()orService.async_trigger().POST /api/states/<entity_id>- Return type:
- async async_trigger_service(domain, service, **service_data)
Tells Home Assistant to trigger a service, returns all states changed while in the process of being called.
POST /api/services/<domain>/<service>
- async async_trigger_service_with_response(domain, service, **service_data)
Tells Home Assistant to trigger a service, returns the response from the service call.
POST /api/services/<domain>/<service>Returns a list of the states changed and the response from the service call.
- check_api_config()
Asks Home Assistant to validate its configuration file.
POST /api/config/core/check_config- Return type:
- static construct_params(params)
Custom method for constructing non-standard query strings.
For keys with corresponding None values, the query string will be key only (i.e.
?key1&key2). For keys with corresponding non-None values, the query string will be key-value pairs (i.e.?key1=value1&key2=value2). To have an empty value use an empty string""(i.e.?key1=&key2=value2).- Return type:
- fire_event(event_type, **event_data)
Fires a given event_type within homeassistant. Must be an existing event_type. POST /api/events/<event_type>
- get_components()
Returns a tuple of all registered components.
GET /api/components
- get_config()
Returns the yaml configuration of homeassistant.
GET /api/config
- get_domain(domain_id)
Fetches all
Service’s under a particular serviceDomain. Uses cached data fromget_domains()if available.
- get_entities()
Fetches all entities from the api and returns them as a dictionary of
Group’s.GET /api/states
- get_entity(group_id=None, slug=None, entity_id=None)
Returns an
Entitymodel for anentity_id.GET /api/states/<entity_id>
- get_entity_histories(entities=None, start_timestamp=None, end_timestamp=None, significant_changes_only=False)
Yields entity state histories. See docs on the
Historymodel.GET /api/history/period/<timestamp>
- get_event(name)
Gets the
Eventwith the specified name if it has at least one listener. Uses cached data fromget_events()if available.
- get_events()
Gets the Events that happen within homeassistant
GET /api/events
- get_logbook_entries(*args, **kwargs)
Returns a list of logbook entries from homeassistant.
GET /api/logbook/<timestamp>- Return type:
- get_rendered_template(template)
Renders a Jinja2 template with Home Assistant context data. See https://www.home-assistant.io/docs/configuration/templating.
POST /api/template- Return type:
- get_state(*, entity_id=None, group_id=None, slug=None)
Fetches the state of the entity specified.
GET /api/states/<entity_id>- Return type:
- get_states()
Gets the states of all entities within homeassistant.
GET /api/states
- static prepare_get_entity_histories_params(entities=None, start_timestamp=None, end_timestamp=None, significant_changes_only=False)
Pre-logic for
Client.get_entity_histories()andClient.async_get_entity_histories().Ensure timestamps :rtype:
Tuple[Dict[str,Optional[str]],str]use second resolution (microseconds are truncated)
are timezone-aware
are URL-encoded (as
construct_params()is used instead of request’s default parameter encoding)
- static prepare_get_logbook_entry_params(filter_entities=None, start_timestamp=None, end_timestamp=None)
Prepares the query string and url path for retrieving logbook entries.
- prepare_headers(headers=None)
Prepares and verifies dictionary headers.
- request(path, *, params='', method='GET', headers=None, decode_bytes=True, **kwargs)
Base method for making requests to the api
- Return type:
- classmethod response_logic(response, decode_bytes=True)
Processes responses from the API and formats them
- Return type:
- set_state(state)
This method sets the representation of a device within Home Assistant and will not communicate with the actual device. To communicate with the device, use
Service.trigger()orService.async_trigger().POST /api/states/<entity_id>- Return type:
- trigger_service(domain, service, **service_data)
Tells Home Assistant to trigger a service, returns all states changed while in the process of being called.
POST /api/services/<domain>/<service>
- trigger_service_with_response(domain, service, **service_data)
Tells Home Assistant to trigger a service, returns the response from the service call.
POST /api/services/<domain>/<service>Returns a list of the states changed and the response from the service call.
- pydantic model homeassistant_api.State
A model representing a state of an entity.
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
attributes (dict[str, JSONType])context (homeassistant_api.models.states.Context | None)entity_id (str)last_changed (datetime.datetime)last_reported (datetime.datetime | None)last_updated (datetime.datetime | None)state (str)
-
field last_changed:
Annotated[datetime] [Optional] The last time the state was changed.
- Constraints:
func = <function <lambda> at 0x7c1a60141360>
return_type = <class ‘str’>
when_used = json
- pydantic model homeassistant_api.Context
Model for entity state contexts.
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
id (str)parent_id (str | None)user_id (str | None)
-
field parent_id:
Optional[str] [Required] Unique string identifying the parent context.
- Constraints:
max_length = 128
- pydantic model homeassistant_api.Domain
Model representing the domain that services belong to.
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
domain_id (str)services (Dict[str, homeassistant_api.models.domains.Service])
- field domain_id: str [Required]
The name of the domain that services belong to. (e.g.
frontendinfrontend.reload_themes
- field services: Dict[str, 'Service'] = {}
A dictionary of all services belonging to the domain indexed by their names
- classmethod from_json(json, client)
Constructs Domain and Service models from json data.
- Return type:
- pydantic model homeassistant_api.Service
Model representing services from homeassistant
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
description (str | None)domain (homeassistant_api.models.domains.Domain)fields (Dict[str, homeassistant_api.models.domains.ServiceField | homeassistant_api.models.domains.ServiceFieldCollection] | None)name (str)response (homeassistant_api.models.domains.ServiceResponse | None)service_id (str)target (homeassistant_api.models.domains.ServiceFieldSelectorTarget | None)
- field service_id: str [Required]
- field domain: Domain [Required]
- field name: str [Required]
- field description: Optional[str] = None
- field fields: Optional[Dict[str, Union[ServiceField, ServiceFieldCollection]]] = None
- field target: Optional[ServiceFieldSelectorTarget] = None
- field response: Optional[ServiceResponse] = None
- trigger(**service_data)
Triggers the service associated with this object.
- pydantic model homeassistant_api.Group
Represents the groups that entities belong to.
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
entities (Dict[str, homeassistant_api.models.entity.Entity])group_id (str)
- pydantic model homeassistant_api.Entity
Represents entities inside of homeassistant
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
group (homeassistant_api.models.entity.Group)slug (str)state (homeassistant_api.models.states.State)
- get_state()
Asks Home Assistant for the state of the entity and updates it locally
- Return type:
- update_state()
Tells Home Assistant to set its current local State object. (You can modify the local state object yourself.)
- Return type:
- get_history(start_timestamp=None, end_timestamp=None, significant_changes_only=False)
- async async_get_state()
Asks Home Assistant for the state of the entity and sets it locally
- Return type:
- async async_update_state()
Tells Home Assistant to set the current local State object.
- Return type:
- pydantic model homeassistant_api.History
Model representing past
State’s of an entity.- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
states (Tuple[homeassistant_api.models.states.State, ...])
- pydantic model homeassistant_api.Event
Event class for Home Assistant Event Triggers
For attribute information see the Data Science docs on Event models https://data.home-assistant.io/docs/events
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
event (str)listener_count (int)
-
field listener_count:
int[Required] How many listeners are interesting in this event in Home Assistant.
- async async_fire(**event_data)
Fires the event type in homeassistant. Ex. on_startup
- Return type:
- pydantic model homeassistant_api.LogbookEntry
Model representing entries in the Logbook.
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
context_id (str | None)domain (str | None)entity_id (str | None)icon (str | None)message (str | None)name (str)state (str | None)when (datetime.datetime)
- class homeassistant_api.WebsocketClient(api_url, token)
The main class for interactign with the Home Assistant WebSocket API client.
Here’s a quick example of how to use the
WebsocketClientclass:from homeassistant_api import WebsocketClient with WebsocketClient( '<WS API Server URL>', # i.e. 'ws://homeassistant.local:8123/api/websocket' '<Your Long Lived Access-Token>' ) as ws_client: light = ws_client.trigger_service('light', 'turn_on', entity_id="light.living_room")
- get_rendered_template(template)
Renders a Jinja2 template with Home Assistant context data. See https://www.home-assistant.io/docs/configuration/templating.
Sends command
{"type": "render_template", ...}.- Return type:
- get_config()
Get the Home Assistant configuration.
Sends command
{"type": "get_config", ...}.
- get_states()
Get a list of states.
Sends command
{"type": "get_states", ...}.
- get_state(*, entity_id=None, group_id=None, slug=None)
Just calls the
get_states()method and filters the result.Please tell home-assistant/core to add a
{"type": "get_state", ...}command to the WS API! There is a lot of disappointment and frustration in the community because this is not available.- Return type:
- get_entities()
Fetches all entities from the Websocket API and returns them as a dictionary of
Group’s. For examplelight.living_roomwould be in the grouplight(i.e.get_entities()["light"].living_room).
- get_entity(group_id=None, slug=None, entity_id=None)
Returns an
Entitymodel for anentity_id.Calls
get_states()under the hood.Please tell home-assistant/core to add a
{"type": "get_state", ...}command to the WS API! There is a lot of disappointment and frustration in the community because this is not available.
- get_domains()
Get a list of services that Home Assistant offers (organized into a dictionary of service domains).
For example, the service
light.turn_onwould be in the domainlight.Sends command
{"type": "get_services", ...}.
- get_domain(domain)
Get a domain.
Note: This is not a method in the WS API client… yet.
Please tell home-assistant/core to add a get_domain command to the WS API!
For now, just call the :py:meth”:get_domains method and parsing the result.
- Return type:
- trigger_service(domain, service, entity_id=None, **service_data)
Trigger a service (that doesn’t return a response).
Sends command
{"type": "call_service", ...}.- Return type:
- trigger_service_with_response(domain, service, entity_id=None, **service_data)
Trigger a service (that returns a response) and return the response.
Sends command
{"type": "call_service", ...}.
- listen_events(event_type=None)
Listen for all events of a certain type.
For example, to listen for all events of type test_event:
with ws_client.listen_events("test_event") as events: for i, event in zip(range(2), events): # to only wait for two events to be received print(event)
- listen_trigger(trigger, **trigger_fields)
Listen to a Home Assistant trigger. Allows additional trigger keyword parameters with
**kwargs(i.e. passingtag_id=...for NFC tag triggers).For example, in Home Assistant Automations we can subscribe to a state trigger for a light entity with YAML:
triggers: # ... - trigger: state entity_id: light.kitchen
To subscribe to that same state trigger with
WebsocketClientinsteadwith ws_client.listen_trigger("state", entity_id="light.kitchen") as trigger: for event in trigger: # will iterate until we manually break out of the loop print(event) if <some_condition>: break # exiting the context manager unsubscribes from the trigger
Woohoo! We can now listen to triggers in Python code!
- fire_event(event_type, **event_data)
Fire an event.
Sends command
{"type": "fire_event", ...}.- Return type:
- ping_latency()
Get the latency (in milliseconds) of the connection by sending a ping message.
- Return type:
- recv(id)
Receive a response to a message from the websocket server.
- Return type:
Union[EventResponse,ResultResponse,PingResponse]
- send(type, include_id=True, **data)
Send a command message to the websocket server and wait for a “result” response.
Returns the id of the message sent.
- Return type:
- pydantic model homeassistant_api.AuthInvalid
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
message (str)type (Literal['auth_invalid'])
- pydantic model homeassistant_api.AuthOk
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
ha_version (str)type (Literal['auth_ok'])
- pydantic model homeassistant_api.AuthRequired
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
ha_version (str)type (Literal['auth_required'])
- pydantic model homeassistant_api.ResultResponse
Result websocket response model.
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
id (int)result (Any | None)success (Literal[True])type (Literal['result'])
- pydantic model homeassistant_api.ErrorResponse
Error websocket response model.
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
error (homeassistant_api.models.websocket.Error)id (int)success (Literal[False])type (Literal['result'])
-
field error:
Error[Required]
- pydantic model homeassistant_api.PingResponse
Ping websocket response model.
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
end (int | None)id (int)start (int)type (Literal['pong'])
- pydantic model homeassistant_api.EventResponse
A model to parse the response of a fired event websocket response.
- Config:
arbitrary_types_allowed: bool = True
validate_assignment: bool = True
extra: str = forbid
protected_namespaces: tuple = ()
- Fields:
event (homeassistant_api.models.websocket.FiredEvent | homeassistant_api.models.websocket.FiredTrigger | homeassistant_api.models.websocket.TemplateEvent)id (int)type (Literal['event'])
-
field event:
Union[FiredEvent,FiredTrigger,TemplateEvent] [Required]