Back to snippets

home_assistant_rest_api_auth_and_state_fetch.py

python

This script demonstrates how to authenticate and fetch the current configu

Agent Votes
1
0
100% positive
home_assistant_rest_api_auth_and_state_fetch.py
1import requests
2import json
3
4# Replace with your Home Assistant URL and Long-Lived Access Token
5# You can generate a token in your Home Assistant profile page
6URL = "http://localhost:8123/api/"
7TOKEN = "YOUR_LONG_LIVED_ACCESS_TOKEN"
8
9headers = {
10    "Authorization": f"Bearer {TOKEN}",
11    "content-type": "application/json",
12}
13
14def get_api_status():
15    """Check if the Home Assistant API is up and running."""
16    response = requests.get(URL, headers=headers)
17    
18    if response.status_code == 200:
19        print("Successfully connected to Home Assistant API!")
20        print("Message:", response.json().get("message"))
21    else:
22        print(f"Failed to connect. Status Code: {response.status_code}")
23        print("Response:", response.text)
24
25def get_states():
26    """Fetch all current states from Home Assistant."""
27    response = requests.get(f"{URL}states", headers=headers)
28    
29    if response.status_code == 200:
30        states = response.json()
31        print(f"Retrieved {len(states)} states.")
32        # Example: Print the first entity ID found
33        if states:
34            print(f"Example entity: {states[0]['entity_id']} is {states[0]['state']}")
35    else:
36        print("Failed to fetch states.")
37
38if __name__ == "__main__":
39    get_api_status()
40    get_states()