Claude
Skills
Sign in
Back

ha-api

Included with Lifetime
$97 forever

Integrate with Home Assistant REST and WebSocket APIs. Use when making API calls, managing entity states, calling services, subscribing to events, or setting up authentication. Activates on keywords REST API, WebSocket, API endpoint, service call, access token, Bearer token, subscribe_events.

Backend & APIs

What this skill does


# Home Assistant API Integration

> Master Home Assistant's REST and WebSocket APIs for external integration, state management, and real-time communication.

## ⚠️ BEFORE YOU START

**This skill prevents 5 common API integration errors and saves ~30% token overhead.**

| Aspect | Details |
|--------|---------|
| Common Errors Prevented | 5+ (auth, WebSocket lifecycle, state format, error handling) |
| Token Savings | ~30% vs. manual API discovery |
| Setup Time | 2-5 minutes vs. 15-20 minutes manual |

### Known Issues This Skill Prevents

1. **Incorrect authentication headers** - Bearer tokens must be prefixed with "Bearer " in Authorization header
2. **WebSocket lifecycle management** - Missing auth_required handling or improper state subscription
3. **State format mismatches** - Confusing state vs. attributes; incorrect JSON payload structure
4. **Error response handling** - Not distinguishing between 4xx client errors and 5xx server errors
5. **Service call domain/service mismatch** - Incorrect routing to service endpoints

## Quick Start

### Step 1: Authentication Setup

```bash
# In Home Assistant UI:
# Settings → My Home → Create Long-Lived Access Token
# Store token securely (never commit to git)

export HA_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
export HA_URL="http://192.168.1.100:8123"
```

**Why this matters:** All API requests require Bearer token authentication. Creating a dedicated token for external apps allows you to revoke access without changing your password.

### Step 2: Test REST API Connectivity

```bash
# Get all entity states
curl -X GET "${HA_URL}/api/states" \
  -H "Authorization: Bearer ${HA_TOKEN}" \
  -H "Content-Type: application/json"
```

**Why this matters:** Verifies your Home Assistant instance is accessible and your token is valid before building complex integrations.

### Step 3: Choose API Type

- **REST API**: For one-time requests, state queries, service calls (HTTP polling)
- **WebSocket API**: For real-time events, continuous subscriptions, lower latency (~50ms vs. seconds)

**Why this matters:** Different use cases require different APIs. WebSocket excels at real-time apps; REST is simpler for occasional requests.

## Critical Rules

### ✅ Always Do

- ✅ Store access tokens in environment variables or secure vaults (never hardcode)
- ✅ Include "Bearer " prefix in Authorization header (exact case and spacing required)
- ✅ Validate WebSocket auth_required messages before sending other commands
- ✅ Handle HTTP errors (401 = token invalid/expired, 404 = entity not found, 502 = HA unavailable)
- ✅ Specify full domain/service for service calls (e.g., "light/turn_on" not just "turn_on")

### ❌ Never Do

- ❌ Commit access tokens to git or share in logs
- ❌ Skip the initial WebSocket auth handshake
- ❌ Mix Bearer token authentication with username/password
- ❌ Assume state values are always strings (can be "on", 123, or null)
- ❌ Call service endpoints with entity_id as path parameter (use JSON payload instead)

### Common Mistakes

**❌ Wrong - Missing Bearer prefix:**
```bash
curl -X GET "http://ha:8123/api/states" \
  -H "Authorization: ${HA_TOKEN}"  # Missing "Bearer "
```

**✅ Correct - Bearer prefix required:**
```bash
curl -X GET "http://ha:8123/api/states" \
  -H "Authorization: Bearer ${HA_TOKEN}"
```

**Why:** Home Assistant's API uses standard Bearer token authentication. The "Bearer " prefix tells the server this is a token-based auth scheme, not a username/password.

## REST API Endpoints Reference

### States Endpoint

**Get all states:**
```bash
GET /api/states
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
[
  {
    "entity_id": "light.living_room",
    "state": "on",
    "attributes": {
      "brightness": 255,
      "color_mode": "color_temp",
      "friendly_name": "Living Room Light"
    },
    "last_changed": "2025-12-31T18:00:00+00:00",
    "last_updated": "2025-12-31T18:05:00+00:00"
  }
]
```

**Get single entity state:**
```bash
GET /api/states/{entity_id}
Authorization: Bearer {token}
```

**Create/update entity state:**
```bash
POST /api/states/{entity_id}
Authorization: Bearer {token}
Content-Type: application/json

{
  "state": "on",
  "attributes": {
    "friendly_name": "Custom Entity",
    "custom_attribute": "value"
  }
}
```

**Response (201 Created or 200 OK):**
```json
{
  "entity_id": "sensor.custom_sensor",
  "state": "on",
  "attributes": { ... }
}
```

### Services Endpoint

**Get all available services:**
```bash
GET /api/services
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
[
  {
    "domain": "light",
    "services": {
      "turn_on": {
        "description": "Turn on light(s)",
        "fields": {
          "entity_id": {
            "description": "The entity_id of the light(s)",
            "example": ["light.living_room", "light.bedroom"]
          },
          "brightness": {
            "description": "Brightness 0-255",
            "example": 180
          }
        }
      },
      "turn_off": { ... }
    }
  }
]
```

**Call a service:**
```bash
POST /api/services/{domain}/{service}
Authorization: Bearer {token}
Content-Type: application/json

{
  "entity_id": "light.living_room",
  "brightness": 180,
  "transition": 2
}
```

**Response (200 OK):**
```json
[
  {
    "entity_id": "light.living_room",
    "state": "on",
    "attributes": { ... }
  }
]
```

### Events Endpoint

**Get all events:**
```bash
GET /api/events
Authorization: Bearer {token}
```

**Fire an event:**
```bash
POST /api/events/{event_type}
Authorization: Bearer {token}
Content-Type: application/json

{
  "custom_data": "value"
}
```

### History Endpoint

**Get entity history:**
```bash
GET /api/history/period/{timestamp}?filter_entity_id={entity_id}
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
[
  [
    {
      "entity_id": "sensor.temperature",
      "state": "22.5",
      "attributes": { ... },
      "last_changed": "2025-12-31T12:00:00+00:00"
    }
  ]
]
```

### Config Endpoint

**Get Home Assistant configuration:**
```bash
GET /api/config
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
  "latitude": 52.3,
  "longitude": 4.9,
  "elevation": 0,
  "unit_system": {
    "length": "km",
    "mass": "kg",
    "temperature": "°C",
    "volume": "L"
  },
  "time_zone": "Europe/Amsterdam",
  "components": ["light", "switch", "sensor", ...]
}
```

### Template Endpoint

**Render a template:**
```bash
POST /api/template
Authorization: Bearer {token}
Content-Type: application/json

{
  "template": "{{ states('sensor.temperature') }}"
}
```

**Response (200 OK):**
```json
{
  "template": "{{ states('sensor.temperature') }}",
  "result": "22.5"
}
```

## WebSocket API Reference

### Connection Flow

1. **Open WebSocket connection to `/api/websocket`**
2. **Receive auth_required message** (must respond within 10 seconds)
3. **Send auth message with token**
4. **Receive auth_ok confirmation**
5. **Send subscriptions/commands**
6. **Receive responses and events in real-time**

### WebSocket Commands

**Authentication:**
```javascript
// Message 1: Server sends (automatically)
{
  "type": "auth_required",
  "ha_version": "2025.1.0"
}

// Message 2: Client responds
{
  "type": "auth",
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

// Message 3: Server confirms
{
  "type": "auth_ok",
  "ha_version": "2025.1.0"
}
```

**Subscribe to events:**
```javascript
{
  "id": 1,
  "type": "subscribe_events",
  "event_type": "state_changed"
}

// Responses come as:
{
  "id": 1,
  "type": "event",
  "event": {
    "type": "state_changed",
    "data": {
      "entity_id": "light.living_room",
      "old_state": { "state": "off", ... },
      "new_state": { "state": "on", ... }
    }
  }
}
```

**Call a service:**
```javascript
{
  "id": 2,
  "type": "call_service",
  "domain": "light",
  "service": "turn_on",
  "service_data": {
    "entity_id": "light.living_room",
    "brightness": 200
  }
}

// Response:
{
  "id": 2,

Related in Backend & APIs