Code Reference

Here you can find a detailed reference for most classes and methods in the library.

Clients

class homeassistant_api.Client(*args, session=None, verify_ssl=True, **kwargs)

The sync client for interacting with Home Assistant via the REST API.

Parameters:
  • api_url – The location of the api endpoint. e.g. http://localhost:8123/api Required.

  • token – The refresh or long lived access token to authenticate your requests. Required.

  • session (Session | None) – A custom niquests.Session instance. Optional.

  • verify_ssl (bool) – Whether to verify SSL certificates. Default True.

  • global_request_kwargs – Kwargs to pass to niquests.Session.request(). Optional.

request(path, *, params=None, method=<HTTPMethod.GET>, headers=None, **kwargs)

Base method for making requests to the api

Return type:

Any

static response_logic(response)

Processes responses from the API and formats them

Return type:

Any

get_error_log()

Returns the server error log as a string. GET /api/error_log

Return type:

str

get_config()

Returns the configuration of Home Assistant. GET /api/config

Return type:

dict[str, Any]

get_logbook_entries(*args, **kwargs)

Returns a list of logbook entries from Home Assistant. GET /api/logbook/<timestamp>

Return type:

Generator[LogbookEntry, None, None]

get_entity_histories(entities=None, start_timestamp=None, end_timestamp=None, *, significant_changes_only=False)

Yields entity state histories. See docs on the History model. GET /api/history/period/<timestamp>

Return type:

Generator[History, None, None]

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:

str

check_api_config()

Asks Home Assistant to validate its configuration file. POST /api/config/core/check_config

Return type:

bool

check_api_running()

Asks Home Assistant if it is running. GET /api/

Return type:

bool

get_entities()

Fetches all entities from the api and returns them as a dictionary of Group’s. GET /api/states

Return type:

dict[str, Group]

get_entity(group_id=None, slug=None, entity_id=None)

Returns an Entity model for an entity_id. GET /api/states/<entity_id>

Return type:

Entity | None

get_domains()

Fetches all service Domain’s from the API. GET /api/services

Return type:

dict[str, Domain]

get_domain(domain_id)

Fetches all Service’s under a particular service Domain. Uses cached data from get_domains() if available.

Return type:

Domain | None

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>

Return type:

tuple[State, ...]

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.

Return type:

tuple[tuple[State, ...], dict[str, Any]]

get_state(*, entity_id=None, group_id=None, slug=None)

Fetches the state of the entity specified. GET /api/states/<entity_id>

Return type:

State

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(). POST /api/states/<entity_id>

Return type:

State

get_states()

Gets the states of all entities within Home Assistant. GET /api/states

Return type:

tuple[State, ...]

get_events()

Gets the Events that happen within Home Assistant. GET /api/events

Return type:

tuple[Event, ...]

get_event(name)

Gets the Event with the specified name if it has at least one listener. Uses cached data from get_events() if available.

Return type:

Event | None

fire_event(event_type, **event_data)

Fires a given event_type within Home Assistant. POST /api/events/<event_type>

Return type:

str

get_components()

Returns a tuple of all registered components. GET /api/components

Return type:

tuple[str, ...]

class homeassistant_api.AsyncClient(*args, session=None, verify_ssl=True, **kwargs)

The async client for interacting with Home Assistant via the REST API.

Parameters:
  • api_url – The location of the api endpoint. e.g. http://localhost:8123/api Required.

  • token – The refresh or long lived access token to authenticate your requests. Required.

  • session (AsyncSession | None) – A custom niquests.AsyncSession instance. Optional.

  • verify_ssl (bool) – Whether to verify SSL certificates. Default True.

  • global_request_kwargs – Kwargs to pass to niquests.AsyncSession.request(). Optional.

async request(path, *, params=None, method=<HTTPMethod.GET>, headers=None, **kwargs)

Base method for making requests to the api

Return type:

Any

async static response_logic(response)

Processes custom mimetype content asynchronously.

Return type:

Any

async get_error_log()

Returns the server error log as a string. GET /api/error_log

Return type:

str

async get_config()

Returns the configuration of Home Assistant. GET /api/config

Return type:

dict[str, Any]

async get_logbook_entries(*args, **kwargs)

Returns a list of logbook entries from Home Assistant. GET /api/logbook/<timestamp>

Return type:

AsyncGenerator[LogbookEntry, None]

async get_entity_histories(entities=None, start_timestamp=None, end_timestamp=None, *, significant_changes_only=False)

Yields entity state histories. See docs on the History model. GET /api/history/period/<timestamp>

Return type:

AsyncGenerator[History, None]

async get_rendered_template(template)

Renders a given Jinja2 template string with Home Assistant context data. POST /api/template

Return type:

str

async check_api_config()

Asks Home Assistant to validate its configuration file. POST /api/config/core/check_config

Return type:

bool

async check_api_running()

Asks Home Assistant if it is running. GET /api/

Return type:

bool

async get_entities()

Fetches all entities from the api and returns them as a dictionary of AsyncGroup’s. GET /api/states

Return type:

dict[str, AsyncGroup]

async get_entity(group_id=None, slug=None, entity_id=None)

Returns an AsyncEntity model for an entity_id. GET /api/states/<entity_id>

Return type:

AsyncEntity | None

async get_domains()

Fetches all service AsyncDomain’s from the API. GET /api/services

Return type:

dict[str, AsyncDomain]

async get_domain(domain_id)

Fetches all AsyncService’s under a particular service AsyncDomain. Uses cached data from get_domains() if available.

Return type:

AsyncDomain | None

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>

Return type:

tuple[State, ...]

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.

Return type:

tuple[tuple[State, ...], dict[str, Any]]

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:

State

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 AsyncService.trigger(). POST /api/states/<entity_id>

Return type:

State

async get_states()

Gets the states of all entities within Home Assistant. GET /api/states

Return type:

tuple[State, ...]

async get_events()

Gets the Events that happen within Home Assistant. GET /api/events

Return type:

tuple[AsyncEvent, ...]

async get_event(name)

Gets the AsyncEvent with the specified name if it has at least one listener. Uses cached data from get_events() if available.

Return type:

AsyncEvent | None

async fire_event(event_type, **event_data)

Fires a given event_type within Home Assistant. POST /api/events/<event_type>

Return type:

str

async get_components()

Returns a tuple of all registered components. GET /api/components

Return type:

tuple[str, ...]

class homeassistant_api.BaseClient(api_url, token, *, global_request_kwargs=None)

Builds, and makes requests to the API

endpoint(*path)

Joins the api base url with a local path to an absolute url

Return type:

str

prepare_headers(headers=None)

Prepares and verifies dictionary headers.

Return type:

dict[str, str]

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:

str

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() and AsyncClient.get_entity_histories().

Ensure timestamps

  • use second resolution (microseconds are truncated)

  • are timezone-aware

  • are URL-encoded (as construct_params() is used instead of request’s default parameter encoding)

Return type:

tuple[dict[str, str | None], str]

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.

Return type:

tuple[dict[str, str], str]

class homeassistant_api.WebsocketClient(api_url, token, *, max_size=16777216, session=None)
send(msg_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:

int

recv(msg_id)

Receive a response to a message from the websocket server.

Return type:

EventResponse | ResultResponse | PingResponse | None

recv_result(msg_id)

Receive a ResultResponse, raising TypeError if the response is not a ResultResponse.

Return type:

ResultResponse

recv_result_dict(msg_id)

Receive a ResultResponse and return its result as a dict.

Return type:

dict[str, Any]

recv_result_list(msg_id)

Receive a ResultResponse and return its result as a list.

Return type:

list[dict[str, Any]]

recv_event(msg_id)

Receive an EventResponse, raising TypeError if the response is not an EventResponse.

Return type:

EventResponse

recv_ping(msg_id)

Receive a PingResponse, raising TypeError if the response is not a PingResponse.

Return type:

PingResponse

authentication_phase()

Authenticate with the websocket server.

Return type:

AuthOk

supported_features_phase()

Get the supported features from the websocket server.

Return type:

None

ping_latency()

Get the latency (in milliseconds) of the connection by sending a ping message.

Return type:

float

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:

str

get_config()

Returns the configuration of Home Assistant.

Sends command {"type": "get_config", ...}.

Return type:

dict[str, Any]

get_states()

Gets the states of all entities within Home Assistant.

Sends command {"type": "get_states", ...}.

Return type:

tuple[State, ...]

get_state(*, entity_id=None, group_id=None, slug=None)

Fetches the state of the entity specified.

Note: The WebSocket API has no single-entity state command, so this fetches all states and filters.

Sends command {"type": "get_states", ...}.

Return type:

State

get_entities()

Fetches all entities from the Websocket API and returns them as a dictionary of Group’s. For example light.living_room would be in the group light (i.e. get_entities()["light"].living_room).

Return type:

dict[str, Group]

get_entity(group_id=None, slug=None, entity_id=None)

Returns an Entity model for an entity_id.

Note: The WebSocket API has no single-entity state command, so this fetches all states and filters.

Return type:

Entity | None

set_state(state)

Not supported over WebSocket. Use the REST Client instead.

Return type:

State

get_entity_histories(entities=None, start_timestamp=None, end_timestamp=None, significant_changes_only=False)

Not supported over WebSocket. Use the REST Client instead.

Return type:

Generator[History, None, None]

get_domains()

Fetches all service Domain’s from the API.

Sends command {"type": "get_services", ...}.

Return type:

dict[str, Domain]

get_domain(domain_id)

Fetches all Service’s under a particular service Domain.

Note: The WebSocket API has no single-domain command, so this fetches all domains and filters.

Return type:

Domain | None

trigger_service(domain, service, **service_data)

Trigger a service (that doesn’t return a response).

Sends command {"type": "call_service", ...}.

Note: Unlike the REST API, the WebSocket API does not return changed states. Subscribe to state_changed events via listen_events() to track changes.

Return type:

None

trigger_service_with_response(domain, service, **service_data)

Trigger a service (that returns a response) and return the response.

Sends command {"type": "call_service", ...}.

Note: Unlike the REST API, the WebSocket API does not return changed states, only the service response data. Subscribe to state_changed events via listen_events() to track changes.

Return type:

dict[str, Any]

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)
Return type:

Generator[Generator[FiredEvent | FiredTrigger, None, None], None, None]

listen_trigger(trigger, **trigger_fields)

Listen to a Home Assistant trigger. Allows additional trigger keyword parameters with **kwargs (i.e. passing tag_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 WebsocketClient instead

with 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!

Return type:

Generator[Generator[dict[str, Any], None, None], None, None]

get_config_entries()

Get all config entries.

Sends command {"type": "config_entries/get", ...}.

Return type:

tuple[ConfigEntry, ...]

disable_config_entry(entry_id)

Disable a config entry.

Sends command {"type": "config_entries/disable", ...}.

Return type:

DisableEnableResult

enable_config_entry(entry_id)

Enable a config entry.

Sends command {"type": "config_entries/disable", ...}.

Return type:

DisableEnableResult

ignore_config_flow(flow_id, title)

Ignore a config flow.

Sends command {"type": "config_entries/ignore_flow", ...}.

Return type:

None

get_nonuser_flows_in_progress()

Get non-user config flows in progress.

Sends command {"type": "config_entries/flow/progress", ...}.

Return type:

tuple[FlowResult, ...]

get_entry_subentries(entry_id)

Get subentries for a config entry.

Sends command {"type": "config_entries/subentries/list", ...}.

Return type:

tuple[ConfigSubEntry, ...]

delete_entry_subentry(entry_id, subentry_id)

Delete a subentry from a config entry.

Sends command {"type": "config_entries/subentries/delete", ...}.

Return type:

None

list_entity_registry()

List all entity registry entries.

Sends command {"type": "config/entity_registry/list", ...}.

Return type:

tuple[EntityRegistryEntry, ...]

get_entity_registry_entry(entity_id)

Get a single entity registry entry.

Sends command {"type": "config/entity_registry/get", ...}.

Return type:

EntityRegistryEntryExtended

update_entity_registry_entry(parameters)

Update an entity registry entry.

Sends command {"type": "config/entity_registry/update", ...}.

Return type:

EntityRegistryUpdateResult

remove_entity_registry_entry(entity_id)

Remove an entity from the entity registry.

Sends command {"type": "config/entity_registry/remove", ...}.

Return type:

None

listen_config_entries()

Listen for config entry changes.

Sends command {"type": "config_entries/subscribe", ...}.

Return type:

Generator[Generator[list[ConfigEntryEvent], None, None], None, None]

fire_event(event_type, **event_data)

Fires a given event_type within Home Assistant.

Sends command {"type": "fire_event", ...}.

Return type:

Context

class homeassistant_api.AsyncWebsocketClient(api_url, token, *, max_size=16777216, session=None)
async send(msg_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:

int

async recv(msg_id)

Receive a response to a message from the websocket server.

Return type:

EventResponse | ResultResponse | PingResponse | None

async recv_result(msg_id)

Receive a ResultResponse, raising TypeError if the response is not a ResultResponse.

Return type:

ResultResponse

async recv_result_dict(msg_id)

Receive a ResultResponse and return its result as a dict.

Return type:

dict[str, Any]

async recv_result_list(msg_id)

Receive a ResultResponse and return its result as a list.

Return type:

list[dict[str, Any]]

async recv_event(msg_id)

Receive an EventResponse, raising TypeError if the response is not an EventResponse.

Return type:

EventResponse

async recv_ping(msg_id)

Receive a PingResponse, raising TypeError if the response is not a PingResponse.

Return type:

PingResponse

async authentication_phase()

Authenticate with the websocket server.

Return type:

AuthOk

async supported_features_phase()

Get the supported features from the websocket server.

Return type:

None

async ping_latency()

Get the latency (in milliseconds) of the connection by sending a ping message.

Return type:

float

async 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:

str

async get_config()

Returns the configuration of Home Assistant.

Sends command {"type": "get_config", ...}.

Return type:

dict[str, Any]

async get_states()

Gets the states of all entities within Home Assistant.

Sends command {"type": "get_states", ...}.

Return type:

tuple[State, ...]

async get_state(*, entity_id=None, group_id=None, slug=None)

Fetches the state of the entity specified.

Note: The WebSocket API has no single-entity state command, so this fetches all states and filters.

Sends command {"type": "get_states", ...}.

Return type:

State

async get_entities()

Fetches all entities from the Websocket API and returns them as a dictionary of AsyncGroup’s. For example light.living_room would be in the group light (i.e. get_entities()["light"].living_room).

Return type:

dict[str, AsyncGroup]

async get_entity(group_id=None, slug=None, entity_id=None)

Returns an AsyncEntity model for an entity_id.

Note: The WebSocket API has no single-entity state command, so this fetches all states and filters.

Return type:

AsyncEntity | None

async set_state(state)

Not supported over WebSocket. Use the REST AsyncClient instead.

Return type:

State

async get_entity_histories(entities=None, start_timestamp=None, end_timestamp=None, significant_changes_only=False)

Not supported over WebSocket. Use the REST AsyncClient instead.

Return type:

AsyncGenerator[History, None]

async get_domains()

Fetches all service AsyncDomain’s from the API.

Sends command {"type": "get_services", ...}.

Return type:

dict[str, AsyncDomain]

async get_domain(domain_id)

Fetches all AsyncService’s under a particular service AsyncDomain.

Note: The WebSocket API has no single-domain command, so this fetches all domains and filters.

Return type:

AsyncDomain | None

async trigger_service(domain, service, **service_data)

Trigger a service (that doesn’t return a response).

Sends command {"type": "call_service", ...}.

Note: Unlike the REST API, the WebSocket API does not return changed states. Subscribe to state_changed events via listen_events() to track changes.

Return type:

None

async trigger_service_with_response(domain, service, **service_data)

Trigger a service (that returns a response) and return the response.

Sends command {"type": "call_service", ...}.

Note: Unlike the REST API, the WebSocket API does not return changed states, only the service response data. Subscribe to state_changed events via listen_events() to track changes.

Return type:

dict[str, Any]

listen_events(event_type=None)

Listen for all events of a certain type.

For example, to listen for all events of type test_event:

async with ws_client.listen_events("test_event") as events:
    async for i, event in zip(range(2), events):  # to only wait for two events to be received
        print(event)
Return type:

AsyncGenerator[AsyncGenerator[FiredEvent | FiredTrigger, None], None]

listen_trigger(trigger, **trigger_fields)

Listen to a Home Assistant trigger. Allows additional trigger keyword parameters with **kwargs (i.e. passing tag_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 AsyncWebsocketClient instead

async with ws_client.listen_trigger("state", entity_id="light.kitchen") as trigger:
    async 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!

Return type:

AsyncGenerator[AsyncGenerator[dict[str, Any], None], None]

async get_config_entries()

Get all config entries.

Sends command {"type": "config_entries/get", ...}.

Return type:

tuple[ConfigEntry, ...]

async disable_config_entry(entry_id)

Disable a config entry.

Sends command {"type": "config_entries/disable", ...}.

Return type:

DisableEnableResult

async enable_config_entry(entry_id)

Enable a config entry.

Sends command {"type": "config_entries/disable", ...}.

Return type:

DisableEnableResult

async ignore_config_flow(flow_id, title)

Ignore a config flow.

Sends command {"type": "config_entries/ignore_flow", ...}.

Return type:

None

async get_nonuser_flows_in_progress()

Get non-user config flows in progress.

Sends command {"type": "config_entries/flow/progress", ...}.

Return type:

tuple[FlowResult, ...]

async get_entry_subentries(entry_id)

Get subentries for a config entry.

Sends command {"type": "config_entries/subentries/list", ...}.

Return type:

tuple[ConfigSubEntry, ...]

async delete_entry_subentry(entry_id, subentry_id)

Delete a subentry from a config entry.

Sends command {"type": "config_entries/subentries/delete", ...}.

Return type:

None

async list_entity_registry()

List all entity registry entries.

Sends command {"type": "config/entity_registry/list", ...}.

Return type:

tuple[EntityRegistryEntry, ...]

async get_entity_registry_entry(entity_id)

Get a single entity registry entry.

Sends command {"type": "config/entity_registry/get", ...}.

Return type:

EntityRegistryEntryExtended

async update_entity_registry_entry(parameters)

Update an entity registry entry.

Sends command {"type": "config/entity_registry/update", ...}.

Return type:

EntityRegistryUpdateResult

async remove_entity_registry_entry(entity_id)

Remove an entity from the entity registry.

Sends command {"type": "config/entity_registry/remove", ...}.

Return type:

None

listen_config_entries()

Listen for config entry changes.

Sends command {"type": "config_entries/subscribe", ...}.

Return type:

AsyncGenerator[AsyncGenerator[list[ConfigEntryEvent], None], None]

async fire_event(event_type, **event_data)

Fires a given event_type within Home Assistant.

Sends command {"type": "fire_event", ...}.

Return type:

Context

class homeassistant_api.BaseWebsocketClient(api_url, token, *, max_size=16777216)

Shared methods for Websocket clients.

handle_recv(data)

Handle a received message.

Return type:

None

Data Models

Domain

File for Service and Domain data models

class homeassistant_api.models.domains.AsyncDomain(**data)

Async domain that creates async Service instances.

Fields

Field

Type

Required

Default

client

AsyncClient | AsyncWebsocketClient

Yes

domain_id

str

Yes

services

dict[str, BaseService]

No

factory

classmethod from_json_with_client(json, client)

Constructs Domain and Service models from json data.

Return type:

AsyncDomain

classmethod from_json(json, **kwargs)

Constructs Self model from json data

Return type:

Self

get_service(service_id)

Return a Service with the given service_id, returns None if no such service exists

Return type:

BaseService | None

class homeassistant_api.models.domains.AsyncService(**data)

Async service with async trigger method.

Fields

Field

Type

Required

Default

description

str | None

No

None

domain

AsyncDomain

Yes

fields

dict[str, ServiceField | ServiceFieldCollection] | None

No

None

name

str | None

No

None

response

ServiceResponse | None

No

None

service_id

str

Yes

target

ServiceFieldSelectorTarget | None

No

None

async trigger(**service_data)

Triggers the service associated with this object.

Return type:

tuple[State, ...] | tuple[tuple[State, ...], dict[str, Any]] | dict[str, Any] | None

class homeassistant_api.models.domains.BaseDomain(**data)

Model representing the domain that services belong to.

Fields

Field

Type

Required

Default

domain_id

str

Yes

services

dict[str, BaseService]

No

factory

classmethod from_json(json, **kwargs)

Constructs Self model from json data

Return type:

Self

get_service(service_id)

Return a Service with the given service_id, returns None if no such service exists

Return type:

BaseService | None

class homeassistant_api.models.domains.BaseService(**data)

Model representing services from homeassistant

Fields

Field

Type

Required

Default

description

str | None

No

None

fields

dict[str, ServiceField | ServiceFieldCollection] | None

No

None

name

str | None

No

None

response

ServiceResponse | None

No

None

service_id

str

Yes

target

ServiceFieldSelectorTarget | None

No

None

class homeassistant_api.models.domains.Domain(**data)

Sync domain that creates sync Service instances.

Fields

Field

Type

Required

Default

client

Client | WebsocketClient

Yes

domain_id

str

Yes

services

dict[str, BaseService]

No

factory

classmethod from_json_with_client(json, client)

Constructs Domain and Service models from json data.

Return type:

Domain

classmethod from_json(json, **kwargs)

Constructs Self model from json data

Return type:

Self

get_service(service_id)

Return a Service with the given service_id, returns None if no such service exists

Return type:

BaseService | None

class homeassistant_api.models.domains.Service(**data)

Sync service with sync trigger method.

Fields

Field

Type

Required

Default

description

str | None

No

None

domain

Domain

Yes

fields

dict[str, ServiceField | ServiceFieldCollection] | None

No

None

name

str | None

No

None

response

ServiceResponse | None

No

None

service_id

str

Yes

target

ServiceFieldSelectorTarget | None

No

None

trigger(**service_data)

Triggers the service associated with this object.

Return type:

tuple[State, ...] | tuple[tuple[State, ...], dict[str, Any]] | dict[str, Any] | None

Entity

Module for Entity and entity Group data models

class homeassistant_api.models.entity.BaseGroup(**data)

Represents the groups that entities belong to.

Fields

Field

Type

Required

Default

entities

dict[str, BaseEntity]

No

factory

group_id

str

Yes

get_entity(slug)

Returns Entity with the given name if it exists. Otherwise returns None

Return type:

Optional[BaseEntity]

class homeassistant_api.models.entity.Group(**data)

Sync group that creates sync Entity instances.

Fields

Field

Type

Required

Default

client

Client | WebsocketClient

Yes

entities

dict[str, BaseEntity]

No

factory

group_id

str

Yes

get_entity(slug)

Returns Entity with the given name if it exists. Otherwise returns None

Return type:

Optional[Entity]

class homeassistant_api.models.entity.AsyncGroup(**data)

Async group that creates async Entity instances.

Fields

Field

Type

Required

Default

client

AsyncClient | AsyncWebsocketClient

Yes

entities

dict[str, BaseEntity]

No

factory

group_id

str

Yes

get_entity(slug)

Returns Entity with the given name if it exists. Otherwise returns None

Return type:

Optional[AsyncEntity]

class homeassistant_api.models.entity.BaseEntity(**data)

Represents entities inside of homeassistant

Fields

Field

Type

Required

Default

group

BaseGroup

Yes

slug

str

Yes

state

State

Yes

property entity_id: str

Constructs the entity_id string from its group and slug

class homeassistant_api.models.entity.Entity(**data)

Sync entity with sync client methods.

Fields

Field

Type

Required

Default

group

Group

Yes

slug

str

Yes

state

State

Yes

get_state()

Asks Home Assistant for the state of the entity and updates it locally

Return type:

State

update_state()

Tells Home Assistant to set its current local State object. (You can modify the local state object yourself.)

Return type:

State

get_history(start_timestamp=None, end_timestamp=None, significant_changes_only=False)

Gets the previous State’s of the Entity

Return type:

History | None

property entity_id: str

Constructs the entity_id string from its group and slug

class homeassistant_api.models.entity.AsyncEntity(**data)

Async entity with async client methods.

Fields

Field

Type

Required

Default

group

AsyncGroup

Yes

slug

str

Yes

state

State

Yes

async get_state()

Asks Home Assistant for the state of the entity and sets it locally

Return type:

State

async update_state()

Tells Home Assistant to set the current local State object.

Return type:

State

async get_history(start_timestamp=None, end_timestamp=None, significant_changes_only=False)

Gets the History of previous State’s of the Entity.

Return type:

History | None

property entity_id: str

Constructs the entity_id string from its group and slug

Event

Event Model File

class homeassistant_api.models.events.BaseEvent(**data)

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

Fields

Field

Type

Required

Default

event

str

Yes

listener_count

int

Yes

classmethod from_json(json, **kwargs)

Constructs Self model from json data

Return type:

Self

class homeassistant_api.models.events.Event(**data)

Sync event with sync fire method.

Fields

Field

Type

Required

Default

client

Client

Yes

event

str

Yes

listener_count

int

Yes

classmethod from_json_with_client(json, client)

Constructs Event model from json data

Return type:

Event

fire(**event_data)

Fires the corresponding event in Home Assistant.

Return type:

str | None

classmethod from_json(json, **kwargs)

Constructs Self model from json data

Return type:

Self

class homeassistant_api.models.events.AsyncEvent(**data)

Async event with async fire method.

Fields

Field

Type

Required

Default

client

AsyncClient

Yes

event

str

Yes

listener_count

int

Yes

classmethod from_json_with_client(json, client)

Constructs Event model from json data

Return type:

AsyncEvent

async fire(**event_data)

Fires the event type in homeassistant.

Return type:

str

classmethod from_json(json, **kwargs)

Constructs Self model from json data

Return type:

Self

History

Module for the History model.

class homeassistant_api.models.history.History(*args, **kwargs)

Model representing past State’s of an entity.

Fields

Field

Type

Required

Default

states

tuple[State, …]

Yes

property entity_id: str

Returns the shared entity_id of states.

Logbook

Module for the Logbook Entry model.

class homeassistant_api.models.logbook.LogbookEntry(**data)

Model representing entries in the Logbook.

Fields

Field

Type

Required

Default

context_id

str | None

No

None

domain

str | None

No

None

entity_id

str | None

No

None

icon

str | None

No

None

message

str | None

No

None

name

str

Yes

state

str | None

No

None

when

datetime

Yes

State

Module for the Entity State model.

class homeassistant_api.models.states.Context(**data)

Model for entity state contexts.

Fields

Field

Type

Required

Default

Constraints

id

str

Yes

max_length=128

parent_id

str | None

Yes

max_length=128

user_id

str | None

Yes

max_length=128

class homeassistant_api.models.states.State(**data)

A model representing a state of an entity.

Fields

Field

Type

Required

Default

attributes

dict[str, Any]

No

factory

context

Context | None

No

None

entity_id

str

Yes

last_changed

datetime

No

factory

last_reported

Annotated[datetime, PlainSerializer(func=~homeassistant_api.models.base., return_type=str, when_used=json)] | None

No

factory

last_updated

Annotated[datetime, PlainSerializer(func=~homeassistant_api.models.base., return_type=str, when_used=json)] | None

No

factory

state

str

Yes

Websocket Models

A module defining the responses we expect from the websocket API.

class homeassistant_api.models.websocket.AuthInvalid(**data)
Fields

Field

Type

Required

Default

message

str

Yes

type

Literal[‘auth_invalid’]

Yes

class homeassistant_api.models.websocket.AuthOk(**data)
Fields

Field

Type

Required

Default

ha_version

str

Yes

type

Literal[‘auth_ok’]

Yes

class homeassistant_api.models.websocket.AuthRequired(**data)
Fields

Field

Type

Required

Default

ha_version

str

Yes

type

Literal[‘auth_required’]

Yes

class homeassistant_api.models.websocket.ErrorResponse(**data)

Error websocket response model.

Fields

Field

Type

Required

Default

error

Error

Yes

id

int

Yes

success

Literal[False]

Yes

type

Literal[‘result’]

Yes

class homeassistant_api.models.websocket.EventResponse(**data)

A model to parse the response of a fired event websocket response.

Fields

Field

Type

Required

Default

event

FiredEvent | FiredTrigger | TemplateEvent | list[ConfigEntryEvent]

Yes

id

int

Yes

type

Literal[‘event’]

Yes

class homeassistant_api.models.websocket.PingResponse(**data)

Ping websocket response model.

Fields

Field

Type

Required

Default

end

int | None

No

None

id

int

Yes

start

int

Yes

type

Literal[‘pong’]

Yes

class homeassistant_api.models.websocket.ResultResponse(**data)

Result websocket response model.

Fields

Field

Type

Required

Default

id

int

Yes

result

Any | None

Yes

success

Literal[True]

Yes

type

Literal[‘result’]

Yes

Request Processing

Module for processing API responses from homeassistant.

class homeassistant_api.processing.ResponseInfo(status_code, url, method)

Extracted metadata from an HTTP response for status code validation.

homeassistant_api.processing.process_response(response)

Process a sync HTTP response: validate status, then parse content.

Return type:

Any

async homeassistant_api.processing.async_process_response(response)

Process an async HTTP response: validate status, then parse content.

Return type:

Any

Errors

Module for custom error classes

exception homeassistant_api.errors.HomeassistantAPIError

Base class for custom errors

exception homeassistant_api.errors.RequestError(data, /, url, message=None)

Error raised when an issue occurs when requesting to Homeassistant.

exception homeassistant_api.errors.RequestTimeoutError(message, url)

Error raised when a request times out.

exception homeassistant_api.errors.ResponseError

Error raised when an issue occurs in a response from Homeassistant.

exception homeassistant_api.errors.BadTemplateError

Error raised when User sends bad template to homeassistant.

exception homeassistant_api.errors.MalformedDataError

Error raised when data from api is not formatted as JSON

exception homeassistant_api.errors.MalformedInputError

Error raised when user passes malformed data in parameters

exception homeassistant_api.errors.APIConfigurationError

Error raised when api says it has an invalid configuration file

exception homeassistant_api.errors.ParameterMissingError

Error raised when an expected attribute is missing from api response data.

exception homeassistant_api.errors.InternalServerError(status_code, content)

Error raised when Home Assistant says that it got itself in trouble.

exception homeassistant_api.errors.UnauthorizedError(message=None)

Error raised when an invalid token in used to authenticate with homeassistant.

exception homeassistant_api.errors.EndpointNotFoundError(path)

Error raised when a request is made to a non existing endpoint.

exception homeassistant_api.errors.MethodNotAllowedError(method)

Error raised when a request is made to an endpoint with a non-allowed method.

exception homeassistant_api.errors.ProcessorNotFoundError

Error raised when a response is encountered that homeassistant_api is not told how to handle.

exception homeassistant_api.errors.UnexpectedStatusCodeError(status_code)

Error raised when a response has an unexpected status code.

exception homeassistant_api.errors.WebsocketError

Error raised when an issue occurs with the websocket connection.

exception homeassistant_api.errors.ReceivingError

Error raised when an issue occurs when receiving a message from the websocket server.