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/api Required.

  • 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() or aiohttp.ClientSession.request(). Optional.

  • cache_session – A requests_cache.CachedSession object to use for caching requests. Optional.

  • async_cache_session – A aiohttp_client_cache.CachedSession object 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:

bool

async async_check_api_running()

Asks Home Assistant if its running. GET /api/

Return type:

bool

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:

str

async async_get_components()

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

Return type:

Tuple[str, ...]

async async_get_config()

Returns the yaml configuration of homeassistant. GET /api/config

Return type:

Dict[str, Any]

async async_get_domain(domain_id)

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

Return type:

Optional[Domain]

async async_get_domains()

Fetches all Service ‘s from the API. GET /api/services

Return type:

Dict[str, Domain]

async async_get_entities()

Fetches all entities from the api. GET /api/states

Return type:

Dict[str, Group]

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>

Return type:

Optional[Entity]

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:

AsyncGenerator[History, None]

async async_get_error_log()

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

Return type:

str

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

Optional[Event]

async async_get_events()

Gets the Events that happen within homeassistant GET /api/events

Return type:

Tuple[Event, ...]

async async_get_logbook_entries(*args, **kwargs)

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

Return type:

AsyncGenerator[LogbookEntry, None]

async async_get_rendered_template(template)

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

Return type:

str

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:

State

async async_get_states()

Gets the states of all entities within homeassistant. GET /api/states

Return type:

Tuple[State, ...]

async async_request(path, method='GET', headers=None, **kwargs)

Base method for making requests to the api

Return type:

Any

async static async_response_logic(response)

Processes custom mimetype content asyncronously.

Return type:

Any

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

Return type:

State

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>

Return type:

Tuple[State, ...]

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.

Return type:

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

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

static construct_params(params)

Custom method for constructing non-standard query strings

Return type:

str

endpoint(*path)

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

Return type:

str

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:

Optional[str]

get_components()

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

Return type:

Tuple[str, ...]

get_config()

Returns the yaml configuration of homeassistant. GET /api/config

Return type:

Dict[str, Any]

get_domain(domain_id)

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

Return type:

Optional[Domain]

get_domains()

Fetches all Service ‘s from the API. GET /api/services

Return type:

Dict[str, Domain]

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:

Optional[Entity]

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_error_log()

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

Return type:

str

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:

Optional[Event]

get_events()

Gets the Events that happen within homeassistant GET /api/events

Return type:

Tuple[Event, ...]

get_logbook_entries(*args, **kwargs)

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

Return type:

Generator[LogbookEntry, 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

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

get_states()

Gets the states of all entities within homeassistant. GET /api/states

Return type:

Tuple[State, ...]

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 Client.async_get_entity_histories.

Return type:

Tuple[Dict[str, Optional[str]], 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]

prepare_headers(headers=None)

Prepares and verifies dictionary headers.

Return type:

Dict[str, str]

request(path, method='GET', headers=None, decode_bytes=True, **kwargs)

Base method for making requests to the api

Return type:

Any

classmethod response_logic(response, decode_bytes=True)

Processes responses from the API and formats them

Return type:

Any

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

Return type:

State

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]]

pydantic model homeassistant_api.State

A model representing a state of an entity.

Show JSON schema
{
   "title": "State",
   "description": "A model representing a state of an entity.",
   "type": "object",
   "properties": {
      "entity_id": {
         "description": "The entity_id this state corresponds to.",
         "title": "Entity Id",
         "type": "string"
      },
      "state": {
         "description": "The string representation of the state of the entity.",
         "title": "State",
         "type": "string"
      },
      "attributes": {
         "default": {},
         "description": "A dictionary of extra attributes of the state.",
         "title": "Attributes",
         "type": "object"
      },
      "last_changed": {
         "description": "The last time the state was changed.",
         "format": "date-time",
         "title": "Last Changed",
         "type": "string"
      },
      "last_updated": {
         "anyOf": [
            {
               "format": "date-time",
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "description": "The last time the state updated.",
         "title": "Last Updated"
      },
      "context": {
         "anyOf": [
            {
               "$ref": "#/$defs/Context"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Provides information about the context of the state."
      }
   },
   "$defs": {
      "Context": {
         "description": "Model for entity state contexts.",
         "properties": {
            "id": {
               "description": "Unique string identifying the context.",
               "maxLength": 128,
               "title": "Id",
               "type": "string"
            },
            "parent_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the parent context.",
               "title": "Parent Id"
            },
            "user_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the user.",
               "title": "User Id"
            }
         },
         "required": [
            "id",
            "parent_id",
            "user_id"
         ],
         "title": "Context",
         "type": "object"
      }
   },
   "required": [
      "entity_id",
      "state"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • attributes (Dict[str, Any])

  • context (homeassistant_api.models.states.Context | None)

  • entity_id (str)

  • last_changed (datetime.datetime)

  • last_updated (datetime.datetime | None)

  • state (str)

field entity_id: str [Required]

The entity_id this state corresponds to.

field state: str [Required]

The string representation of the state of the entity.

field attributes: Dict[str, Any] = {}

A dictionary of extra attributes of the state.

field last_changed: Annotated[datetime] [Optional]

The last time the state was changed.

Constraints:
  • func = <function <lambda> at 0x7f8483017d90>

  • return_type = <class ‘str’>

  • when_used = json

field last_updated: Optional[Annotated[datetime]] [Optional]

The last time the state updated.

field context: Optional[Context] = None

Provides information about the context of the state.

classmethod from_json(json)

Constructs State model from json data

Return type:

State

pydantic model homeassistant_api.Context

Model for entity state contexts.

Show JSON schema
{
   "title": "Context",
   "description": "Model for entity state contexts.",
   "type": "object",
   "properties": {
      "id": {
         "description": "Unique string identifying the context.",
         "maxLength": 128,
         "title": "Id",
         "type": "string"
      },
      "parent_id": {
         "anyOf": [
            {
               "maxLength": 128,
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "description": "Unique string identifying the parent context.",
         "title": "Parent Id"
      },
      "user_id": {
         "anyOf": [
            {
               "maxLength": 128,
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "description": "Unique string identifying the user.",
         "title": "User Id"
      }
   },
   "required": [
      "id",
      "parent_id",
      "user_id"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • id (str)

  • parent_id (str | None)

  • user_id (str | None)

field id: str [Required]

Unique string identifying the context.

Constraints:
  • max_length = 128

field parent_id: Optional[str] [Required]

Unique string identifying the parent context.

Constraints:
  • max_length = 128

field user_id: Optional[str] [Required]

Unique string identifying the user.

Constraints:
  • max_length = 128

classmethod from_json(json)

Constructs Context model from json data

Return type:

Context

pydantic model homeassistant_api.Domain

Model representing the domain that services belong to.

Show JSON schema
{
   "$defs": {
      "Domain": {
         "description": "Model representing the domain that services belong to.",
         "properties": {
            "domain_id": {
               "description": "The name of the domain that services belong to. (e.g. :code:`frontend` in :code:`frontend.reload_themes`",
               "title": "Domain Id",
               "type": "string"
            },
            "services": {
               "additionalProperties": {
                  "$ref": "#/$defs/Service"
               },
               "default": {},
               "description": "A dictionary of all services belonging to the domain indexed by their names",
               "title": "Services",
               "type": "object"
            }
         },
         "required": [
            "domain_id"
         ],
         "title": "Domain",
         "type": "object"
      },
      "Service": {
         "description": "Model representing services from homeassistant",
         "properties": {
            "service_id": {
               "title": "Service Id",
               "type": "string"
            },
            "domain": {
               "$ref": "#/$defs/Domain"
            },
            "name": {
               "anyOf": [
                  {
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Name"
            },
            "description": {
               "anyOf": [
                  {
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Description"
            },
            "fields": {
               "anyOf": [
                  {
                     "additionalProperties": {
                        "$ref": "#/$defs/ServiceField"
                     },
                     "type": "object"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Fields"
            }
         },
         "required": [
            "service_id",
            "domain"
         ],
         "title": "Service",
         "type": "object"
      },
      "ServiceField": {
         "description": "Model for service parameters/fields.",
         "properties": {
            "description": {
               "anyOf": [
                  {
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Description"
            },
            "example": {
               "default": null,
               "title": "Example"
            },
            "selector": {
               "anyOf": [
                  {
                     "type": "object"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Selector"
            },
            "name": {
               "anyOf": [
                  {
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Name"
            },
            "required": {
               "anyOf": [
                  {
                     "type": "boolean"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Required"
            }
         },
         "title": "ServiceField",
         "type": "object"
      }
   },
   "allOf": [
      {
         "$ref": "#/$defs/Domain"
      }
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

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. frontend in frontend.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:

Domain

get_service(service_id)

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

Return type:

Optional[Service]

pydantic model homeassistant_api.Service

Model representing services from homeassistant

Show JSON schema
{
   "$defs": {
      "Domain": {
         "description": "Model representing the domain that services belong to.",
         "properties": {
            "domain_id": {
               "description": "The name of the domain that services belong to. (e.g. :code:`frontend` in :code:`frontend.reload_themes`",
               "title": "Domain Id",
               "type": "string"
            },
            "services": {
               "additionalProperties": {
                  "$ref": "#/$defs/Service"
               },
               "default": {},
               "description": "A dictionary of all services belonging to the domain indexed by their names",
               "title": "Services",
               "type": "object"
            }
         },
         "required": [
            "domain_id"
         ],
         "title": "Domain",
         "type": "object"
      },
      "Service": {
         "description": "Model representing services from homeassistant",
         "properties": {
            "service_id": {
               "title": "Service Id",
               "type": "string"
            },
            "domain": {
               "$ref": "#/$defs/Domain"
            },
            "name": {
               "anyOf": [
                  {
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Name"
            },
            "description": {
               "anyOf": [
                  {
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Description"
            },
            "fields": {
               "anyOf": [
                  {
                     "additionalProperties": {
                        "$ref": "#/$defs/ServiceField"
                     },
                     "type": "object"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Fields"
            }
         },
         "required": [
            "service_id",
            "domain"
         ],
         "title": "Service",
         "type": "object"
      },
      "ServiceField": {
         "description": "Model for service parameters/fields.",
         "properties": {
            "description": {
               "anyOf": [
                  {
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Description"
            },
            "example": {
               "default": null,
               "title": "Example"
            },
            "selector": {
               "anyOf": [
                  {
                     "type": "object"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Selector"
            },
            "name": {
               "anyOf": [
                  {
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Name"
            },
            "required": {
               "anyOf": [
                  {
                     "type": "boolean"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "title": "Required"
            }
         },
         "title": "ServiceField",
         "type": "object"
      }
   },
   "allOf": [
      {
         "$ref": "#/$defs/Service"
      }
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • description (str | None)

  • domain (homeassistant_api.models.domains.Domain)

  • fields (Dict[str, homeassistant_api.models.domains.ServiceField] | None)

  • name (str | None)

  • service_id (str)

field service_id: str [Required]
field domain: Domain [Required]
field name: Optional[str] = None
field description: Optional[str] = None
field fields: Optional[Dict[str, ServiceField]] = None
trigger(entity_id=None, **service_data)

Triggers the service associated with this object.

Return type:

Union[Tuple[State, ...], Tuple[Tuple[State, ...], Dict[str, Any]], dict[str, Any], None]

async async_trigger(entity_id=None, **service_data)

Triggers the service associated with this object.

Return type:

Union[Tuple[State, ...], Tuple[Tuple[State, ...], Dict[str, Any]]]

pydantic model homeassistant_api.Group

Represents the groups that entities belong to.

Show JSON schema
{
   "$defs": {
      "Context": {
         "description": "Model for entity state contexts.",
         "properties": {
            "id": {
               "description": "Unique string identifying the context.",
               "maxLength": 128,
               "title": "Id",
               "type": "string"
            },
            "parent_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the parent context.",
               "title": "Parent Id"
            },
            "user_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the user.",
               "title": "User Id"
            }
         },
         "required": [
            "id",
            "parent_id",
            "user_id"
         ],
         "title": "Context",
         "type": "object"
      },
      "Entity": {
         "description": "Represents entities inside of homeassistant",
         "properties": {
            "slug": {
               "title": "Slug",
               "type": "string"
            },
            "state": {
               "$ref": "#/$defs/State"
            },
            "group": {
               "$ref": "#/$defs/Group"
            }
         },
         "required": [
            "slug",
            "state",
            "group"
         ],
         "title": "Entity",
         "type": "object"
      },
      "Group": {
         "description": "Represents the groups that entities belong to.",
         "properties": {
            "group_id": {
               "description": "A unique string identifying different types/groups of entities.",
               "title": "Group Id",
               "type": "string"
            },
            "entities": {
               "additionalProperties": {
                  "$ref": "#/$defs/Entity"
               },
               "default": {},
               "description": "A dictionary of all entities belonging to the group indexed by their :code:`entity_id`.",
               "title": "Entities",
               "type": "object"
            }
         },
         "required": [
            "group_id"
         ],
         "title": "Group",
         "type": "object"
      },
      "State": {
         "description": "A model representing a state of an entity.",
         "properties": {
            "entity_id": {
               "description": "The entity_id this state corresponds to.",
               "title": "Entity Id",
               "type": "string"
            },
            "state": {
               "description": "The string representation of the state of the entity.",
               "title": "State",
               "type": "string"
            },
            "attributes": {
               "default": {},
               "description": "A dictionary of extra attributes of the state.",
               "title": "Attributes",
               "type": "object"
            },
            "last_changed": {
               "description": "The last time the state was changed.",
               "format": "date-time",
               "title": "Last Changed",
               "type": "string"
            },
            "last_updated": {
               "anyOf": [
                  {
                     "format": "date-time",
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "The last time the state updated.",
               "title": "Last Updated"
            },
            "context": {
               "anyOf": [
                  {
                     "$ref": "#/$defs/Context"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "description": "Provides information about the context of the state."
            }
         },
         "required": [
            "entity_id",
            "state"
         ],
         "title": "State",
         "type": "object"
      }
   },
   "allOf": [
      {
         "$ref": "#/$defs/Group"
      }
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • entities (Dict[str, homeassistant_api.models.entity.Entity])

  • group_id (str)

field group_id: str [Required]

A unique string identifying different types/groups of entities.

field entities: Dict[str, Entity] = {}

A dictionary of all entities belonging to the group indexed by their entity_id.

get_entity(slug)

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

Return type:

Optional[Entity]

pydantic model homeassistant_api.Entity

Represents entities inside of homeassistant

Show JSON schema
{
   "$defs": {
      "Context": {
         "description": "Model for entity state contexts.",
         "properties": {
            "id": {
               "description": "Unique string identifying the context.",
               "maxLength": 128,
               "title": "Id",
               "type": "string"
            },
            "parent_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the parent context.",
               "title": "Parent Id"
            },
            "user_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the user.",
               "title": "User Id"
            }
         },
         "required": [
            "id",
            "parent_id",
            "user_id"
         ],
         "title": "Context",
         "type": "object"
      },
      "Entity": {
         "description": "Represents entities inside of homeassistant",
         "properties": {
            "slug": {
               "title": "Slug",
               "type": "string"
            },
            "state": {
               "$ref": "#/$defs/State"
            },
            "group": {
               "$ref": "#/$defs/Group"
            }
         },
         "required": [
            "slug",
            "state",
            "group"
         ],
         "title": "Entity",
         "type": "object"
      },
      "Group": {
         "description": "Represents the groups that entities belong to.",
         "properties": {
            "group_id": {
               "description": "A unique string identifying different types/groups of entities.",
               "title": "Group Id",
               "type": "string"
            },
            "entities": {
               "additionalProperties": {
                  "$ref": "#/$defs/Entity"
               },
               "default": {},
               "description": "A dictionary of all entities belonging to the group indexed by their :code:`entity_id`.",
               "title": "Entities",
               "type": "object"
            }
         },
         "required": [
            "group_id"
         ],
         "title": "Group",
         "type": "object"
      },
      "State": {
         "description": "A model representing a state of an entity.",
         "properties": {
            "entity_id": {
               "description": "The entity_id this state corresponds to.",
               "title": "Entity Id",
               "type": "string"
            },
            "state": {
               "description": "The string representation of the state of the entity.",
               "title": "State",
               "type": "string"
            },
            "attributes": {
               "default": {},
               "description": "A dictionary of extra attributes of the state.",
               "title": "Attributes",
               "type": "object"
            },
            "last_changed": {
               "description": "The last time the state was changed.",
               "format": "date-time",
               "title": "Last Changed",
               "type": "string"
            },
            "last_updated": {
               "anyOf": [
                  {
                     "format": "date-time",
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "The last time the state updated.",
               "title": "Last Updated"
            },
            "context": {
               "anyOf": [
                  {
                     "$ref": "#/$defs/Context"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "description": "Provides information about the context of the state."
            }
         },
         "required": [
            "entity_id",
            "state"
         ],
         "title": "State",
         "type": "object"
      }
   },
   "allOf": [
      {
         "$ref": "#/$defs/Entity"
      }
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • group (homeassistant_api.models.entity.Group)

  • slug (str)

  • state (homeassistant_api.models.states.State)

field slug: str [Required]
field state: State [Required]
field group: Group [Required]
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

property entity_id: str

Constructs the entity_id string from its group and slug

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

Gets the previous State’s of the Entity

Return type:

Optional[History]

async async_get_state()

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

Return type:

State

async async_update_state()

Tells Home Assistant to set the current local State object.

Return type:

State

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

Optional[History]

pydantic model homeassistant_api.History

Model representing past State’s of an entity.

Show JSON schema
{
   "title": "History",
   "description": "Model representing past :py:class:`State`'s of an entity.",
   "type": "object",
   "properties": {
      "states": {
         "description": "A tuple of previous states of an entity.",
         "items": {
            "$ref": "#/$defs/State"
         },
         "title": "States",
         "type": "array"
      }
   },
   "$defs": {
      "Context": {
         "description": "Model for entity state contexts.",
         "properties": {
            "id": {
               "description": "Unique string identifying the context.",
               "maxLength": 128,
               "title": "Id",
               "type": "string"
            },
            "parent_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the parent context.",
               "title": "Parent Id"
            },
            "user_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the user.",
               "title": "User Id"
            }
         },
         "required": [
            "id",
            "parent_id",
            "user_id"
         ],
         "title": "Context",
         "type": "object"
      },
      "State": {
         "description": "A model representing a state of an entity.",
         "properties": {
            "entity_id": {
               "description": "The entity_id this state corresponds to.",
               "title": "Entity Id",
               "type": "string"
            },
            "state": {
               "description": "The string representation of the state of the entity.",
               "title": "State",
               "type": "string"
            },
            "attributes": {
               "default": {},
               "description": "A dictionary of extra attributes of the state.",
               "title": "Attributes",
               "type": "object"
            },
            "last_changed": {
               "description": "The last time the state was changed.",
               "format": "date-time",
               "title": "Last Changed",
               "type": "string"
            },
            "last_updated": {
               "anyOf": [
                  {
                     "format": "date-time",
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "The last time the state updated.",
               "title": "Last Updated"
            },
            "context": {
               "anyOf": [
                  {
                     "$ref": "#/$defs/Context"
                  },
                  {
                     "type": "null"
                  }
               ],
               "default": null,
               "description": "Provides information about the context of the state."
            }
         },
         "required": [
            "entity_id",
            "state"
         ],
         "title": "State",
         "type": "object"
      }
   },
   "required": [
      "states"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • states (Tuple[homeassistant_api.models.states.State, ...])

field states: Tuple[State, ...] [Required]

A tuple of previous states of an entity.

property entity_id: str

Returns the shared entity_id of states.

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

Show JSON schema
{
   "title": "Event",
   "description": "Event class for Home Assistant Event Triggers\n\nFor attribute information see the Data Science docs on Event models\nhttps://data.home-assistant.io/docs/events",
   "type": "object",
   "properties": {
      "event": {
         "description": "The event name/type.",
         "title": "Event",
         "type": "string"
      },
      "listener_count": {
         "description": "How many listeners are interesting in this event in Home Assistant.",
         "title": "Listener Count",
         "type": "integer"
      }
   },
   "required": [
      "event",
      "listener_count"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • event (str)

  • listener_count (int)

field event: str [Required]

The event name/type.

field listener_count: int [Required]

How many listeners are interesting in this event in Home Assistant.

fire(**event_data)

Fires the corresponding event in Home Assistant.

Return type:

Optional[str]

async async_fire(**event_data)

Fires the event type in homeassistant. Ex. on_startup

Return type:

str

classmethod from_json(json, client)

Constructs Event model from json data

Return type:

Event

pydantic model homeassistant_api.LogbookEntry

Model representing entries in the Logbook.

Show JSON schema
{
   "title": "LogbookEntry",
   "description": "Model representing entries in the Logbook.",
   "type": "object",
   "properties": {
      "when": {
         "description": "When the entry was logged.",
         "format": "date-time",
         "title": "When",
         "type": "string"
      },
      "name": {
         "description": "The name of the entry.",
         "title": "Name",
         "type": "string"
      },
      "message": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Optional message for the entry.",
         "title": "Message"
      },
      "entity_id": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Optional relevant entity_id.",
         "title": "Entity Id"
      },
      "state": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "The new state information of the entity_id.",
         "title": "State"
      },
      "domain": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "When the entry was logged.",
         "title": "Domain"
      },
      "context_id": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Optional relevant context instead of an entity.",
         "title": "Context Id"
      },
      "icon": {
         "anyOf": [
            {
               "type": "string"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "An MDI icon associated with the entity_id.",
         "title": "Icon"
      }
   },
   "required": [
      "when",
      "name"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

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)

field when: Annotated[datetime] [Required]

When the entry was logged.

Constraints:
  • func = <function <lambda> at 0x7f8483017d90>

  • return_type = <class ‘str’>

  • when_used = json

field name: str [Required]

The name of the entry.

field message: Optional[str] = None

Optional message for the entry.

field entity_id: Optional[str] = None

Optional relevant entity_id.

field state: Optional[str] = None

The new state information of the entity_id.

field domain: Optional[str] = None

When the entry was logged.

field context_id: Optional[str] = None

Optional relevant context instead of an entity.

field icon: Optional[str] = None

An MDI icon associated with the entity_id.

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 WebsocketClient class:

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:

str

get_config()

Get the Home Assistant configuration.

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

Return type:

dict[str, Any]

get_states()

Get a list of states.

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

Return type:

Tuple[State, ...]

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:

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.

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.

Return type:

Optional[Entity]

get_domains()

Get a list of services that Home Assistant offers (organized into a dictionary of service domains).

For example, the service light.turn_on would be in the domain light.

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

Return type:

dict[str, Domain]

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:

Domain

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:

None

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", ...}.

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, 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]

fire_event(event_type, **event_data)

Fire an event.

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

Return type:

Context

authentication_phase()

Authenticate with the websocket server.

Return type:

AuthOk

check_success(data)

Check if a command message was successful.

Return type:

None

handle_recv(data)

Handle a received message.

Return type:

None

ping_latency()

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

Return type:

float

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:

int

supported_features_phase()

Get the supported features from the websocket server.

Return type:

None

pydantic model homeassistant_api.AuthInvalid

Show JSON schema
{
   "title": "AuthInvalid",
   "type": "object",
   "properties": {
      "type": {
         "const": "auth_invalid",
         "enum": [
            "auth_invalid"
         ],
         "title": "Type",
         "type": "string"
      },
      "message": {
         "title": "Message",
         "type": "string"
      }
   },
   "required": [
      "type",
      "message"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • message (str)

  • type (Literal['auth_invalid'])

field type: Literal['auth_invalid'] [Required]
field message: str [Required]
pydantic model homeassistant_api.AuthOk

Show JSON schema
{
   "title": "AuthOk",
   "type": "object",
   "properties": {
      "type": {
         "const": "auth_ok",
         "enum": [
            "auth_ok"
         ],
         "title": "Type",
         "type": "string"
      },
      "ha_version": {
         "title": "Ha Version",
         "type": "string"
      }
   },
   "required": [
      "type",
      "ha_version"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • ha_version (str)

  • type (Literal['auth_ok'])

field type: Literal['auth_ok'] [Required]
field ha_version: str [Required]
pydantic model homeassistant_api.AuthRequired

Show JSON schema
{
   "title": "AuthRequired",
   "type": "object",
   "properties": {
      "type": {
         "const": "auth_required",
         "enum": [
            "auth_required"
         ],
         "title": "Type",
         "type": "string"
      },
      "ha_version": {
         "title": "Ha Version",
         "type": "string"
      }
   },
   "required": [
      "type",
      "ha_version"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • ha_version (str)

  • type (Literal['auth_required'])

field type: Literal['auth_required'] [Required]
field ha_version: str [Required]
pydantic model homeassistant_api.ResultResponse

Result websocket response model.

Show JSON schema
{
   "title": "ResultResponse",
   "description": "Result websocket response model.",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "integer"
      },
      "success": {
         "const": true,
         "enum": [
            true
         ],
         "title": "Success",
         "type": "boolean"
      },
      "type": {
         "const": "result",
         "enum": [
            "result"
         ],
         "title": "Type",
         "type": "string"
      },
      "result": {
         "anyOf": [
            {},
            {
               "type": "null"
            }
         ],
         "title": "Result"
      }
   },
   "required": [
      "id",
      "success",
      "type",
      "result"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • id (int)

  • result (Any | None)

  • success (Literal[True])

  • type (Literal['result'])

field id: int [Required]
field success: Literal[True] [Required]
field type: Literal['result'] [Required]
field result: Optional[Any] [Required]
pydantic model homeassistant_api.ErrorResponse

Error websocket response model.

Show JSON schema
{
   "title": "ErrorResponse",
   "description": "Error websocket response model.",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "integer"
      },
      "success": {
         "const": false,
         "enum": [
            false
         ],
         "title": "Success",
         "type": "boolean"
      },
      "type": {
         "const": "result",
         "enum": [
            "result"
         ],
         "title": "Type",
         "type": "string"
      },
      "error": {
         "$ref": "#/$defs/Error"
      }
   },
   "$defs": {
      "Error": {
         "properties": {
            "code": {
               "title": "Code",
               "type": "string"
            },
            "message": {
               "title": "Message",
               "type": "string"
            }
         },
         "required": [
            "code",
            "message"
         ],
         "title": "Error",
         "type": "object"
      }
   },
   "required": [
      "id",
      "success",
      "type",
      "error"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • error (homeassistant_api.models.websocket.Error)

  • id (int)

  • success (Literal[False])

  • type (Literal['result'])

field id: int [Required]
field success: Literal[False] [Required]
field type: Literal['result'] [Required]
field error: Error [Required]
pydantic model homeassistant_api.PingResponse

Ping websocket response model.

Show JSON schema
{
   "title": "PingResponse",
   "description": "Ping websocket response model.",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "integer"
      },
      "type": {
         "const": "pong",
         "enum": [
            "pong"
         ],
         "title": "Type",
         "type": "string"
      },
      "start": {
         "title": "Start",
         "type": "integer"
      },
      "end": {
         "anyOf": [
            {
               "type": "integer"
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "title": "End"
      }
   },
   "required": [
      "id",
      "type",
      "start"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • end (int | None)

  • id (int)

  • start (int)

  • type (Literal['pong'])

field id: int [Required]
field type: Literal['pong'] [Required]
field start: int [Required]
field end: Optional[int] = None
pydantic model homeassistant_api.EventResponse

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

Show JSON schema
{
   "title": "EventResponse",
   "description": "A model to parse the response of a fired event websocket response.",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "integer"
      },
      "type": {
         "const": "event",
         "enum": [
            "event"
         ],
         "title": "Type",
         "type": "string"
      },
      "event": {
         "anyOf": [
            {
               "$ref": "#/$defs/FiredEvent"
            },
            {
               "$ref": "#/$defs/FiredTrigger"
            },
            {
               "$ref": "#/$defs/TemplateEvent"
            }
         ],
         "title": "Event"
      }
   },
   "$defs": {
      "Context": {
         "description": "Model for entity state contexts.",
         "properties": {
            "id": {
               "description": "Unique string identifying the context.",
               "maxLength": 128,
               "title": "Id",
               "type": "string"
            },
            "parent_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the parent context.",
               "title": "Parent Id"
            },
            "user_id": {
               "anyOf": [
                  {
                     "maxLength": 128,
                     "type": "string"
                  },
                  {
                     "type": "null"
                  }
               ],
               "description": "Unique string identifying the user.",
               "title": "User Id"
            }
         },
         "required": [
            "id",
            "parent_id",
            "user_id"
         ],
         "title": "Context",
         "type": "object"
      },
      "FiredEvent": {
         "description": "A model to parse the `event` key of fired event websocket responses.",
         "properties": {
            "event_type": {
               "title": "Event Type",
               "type": "string"
            },
            "data": {
               "title": "Data",
               "type": "object"
            },
            "origin": {
               "enum": [
                  "LOCAL",
                  "REMOTE"
               ],
               "title": "Origin",
               "type": "string"
            },
            "time_fired": {
               "format": "date-time",
               "title": "Time Fired",
               "type": "string"
            },
            "context": {
               "anyOf": [
                  {
                     "$ref": "#/$defs/Context"
                  },
                  {
                     "type": "null"
                  }
               ]
            }
         },
         "required": [
            "event_type",
            "data",
            "origin",
            "time_fired",
            "context"
         ],
         "title": "FiredEvent",
         "type": "object"
      },
      "FiredTrigger": {
         "description": "A model to parse the `trigger` key of fired event websocket responses.",
         "properties": {
            "context": {
               "anyOf": [
                  {
                     "$ref": "#/$defs/Context"
                  },
                  {
                     "type": "null"
                  }
               ]
            },
            "variables": {
               "title": "Variables",
               "type": "object"
            }
         },
         "required": [
            "context",
            "variables"
         ],
         "title": "FiredTrigger",
         "type": "object"
      },
      "TemplateEvent": {
         "properties": {
            "result": {
               "title": "Result",
               "type": "string"
            },
            "listeners": {
               "title": "Listeners",
               "type": "object"
            }
         },
         "required": [
            "result",
            "listeners"
         ],
         "title": "TemplateEvent",
         "type": "object"
      }
   },
   "required": [
      "id",
      "type",
      "event"
   ]
}

Config:
  • arbitrary_types_allowed: bool = True

  • validate_assignment: bool = True

Fields:
  • event (homeassistant_api.models.websocket.FiredEvent | homeassistant_api.models.websocket.FiredTrigger | homeassistant_api.models.websocket.TemplateEvent)

  • id (int)

  • type (Literal['event'])

field id: int [Required]
field type: Literal['event'] [Required]
field event: Union[FiredEvent, FiredTrigger, TemplateEvent] [Required]