Overview
The WebSocket API allows you to:- Subscribe to state changes and events in real-time
- Call services
- Query states and configuration
- Execute commands with responses
- Receive push notifications for updates
homeassistant/components/websocket_api/__init__.py
Connection
Establishing a Connection
Connect to the WebSocket endpoint:Authentication Flow
- Upon connection, you receive an
auth_requiredmessage:
- Send an authentication message with your long-lived access token:
- If successful, you’ll receive:
Create long-lived access tokens in the Home Assistant UI under your user profile.
Message Format
Command Messages
All commands sent to Home Assistant follow this format:id: Unique integer to match responses (required)type: Command type (required)- Additional fields depend on the command
Result Messages
Home Assistant responds with either a success or error result: Success:Error Codes
Fromhomeassistant/components/websocket_api/const.py:
ERR_UNKNOWN_COMMAND: Command is not recognizedERR_INVALID_FORMAT: Message format is invalidERR_NOT_FOUND: Requested resource not foundERR_NOT_ALLOWED: Permission deniedERR_HOME_ASSISTANT_ERROR: Internal Home Assistant errorERR_UNKNOWN_ERROR: Unknown error occurredERR_UNAUTHORIZED: Authentication requiredERR_TIMEOUT: Command timed outERR_NOT_SUPPORTED: Feature not supportedERR_TEMPLATE_ERROR: Template rendering errorERR_SERVICE_VALIDATION_ERROR: Service call validation failed
Common Commands
Subscribe to Events
Subscribe to specific event types:event_type):
Unsubscribe from Events
Get States
Get all entity states:Get Config
Retrieve Home Assistant configuration:Call Service
Execute a service:Ping/Pong
Keep connection alive:Registering Custom Commands
Integrations can register custom WebSocket commands using the@websocket_command decorator:
Async Response Commands
For async operations, use the@async_response decorator:
Permission Requirements
Require admin permissions:Current Connection
Access the current WebSocket connection in async code:Message Helpers
Fromhomeassistant/components/websocket_api/messages.py:
Connection Management
TheActiveConnection class manages WebSocket connections:
Best Practices
Handle Reconnection
Implement automatic reconnection with exponential backoff
Validate Messages
Always validate command parameters with voluptuous schemas
Use Callbacks
Use @callback for sync handlers to avoid blocking the event loop
Clean Up Subscriptions
Unsubscribe from events when no longer needed
Full Example
See Also
REST API
HTTP-based API for polling operations
Event System
Understanding Home Assistant events
Service Calls
Learn about calling services
Authentication
Authentication and permissions system