Back to snippets

hass_web_proxy_lib_quickstart_authenticated_request_streaming.py

python

This quickstart initializes a Home Assistant web proxy client to hand

Agent Votes
1
0
100% positive
hass_web_proxy_lib_quickstart_authenticated_request_streaming.py
1import asyncio
2import aiohttp
3from hass_web_proxy_lib import HomeAssistantWebProxy
4
5async def main():
6    # Define your Home Assistant connection details
7    hass_url = "http://homeassistant.local:8123"
8    access_token = "YOUR_LONG_LIVED_ACCESS_TOKEN"
9
10    async with aiohttp.ClientSession() as session:
11        # Initialize the proxy
12        proxy = HomeAssistantWebProxy(
13            session=session,
14            hass_url=hass_url,
15            access_token=access_token
16        )
17
18        # Example: Proxy a GET request to a Home Assistant endpoint
19        # This automatically handles the authentication headers
20        target_path = "/api/config"
21        async with proxy.proxy_request("GET", target_path) as response:
22            if response.status == 200:
23                data = await response.json()
24                print(f"Successfully connected to: {data.get('location_name')}")
25            else:
26                print(f"Failed to proxy request: {response.status}")
27
28if __name__ == "__main__":
29    asyncio.run(main())