Skip to content

Commit b120ae8

Browse files
authored
Fix webhook exception when empty json data is sent (home-assistant#158254)
1 parent c1227aa commit b120ae8

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

homeassistant/components/webhook/trigger.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from homeassistant.helpers.template import Template
1616
from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
1717
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
18+
from homeassistant.util.json import json_loads
1819

1920
from . import (
2021
DEFAULT_METHODS,
@@ -62,7 +63,9 @@ async def _handle_webhook(
6263
base_result: dict[str, Any] = {"platform": "webhook", "webhook_id": webhook_id}
6364

6465
if "json" in request.headers.get(hdrs.CONTENT_TYPE, ""):
65-
base_result["json"] = await request.json()
66+
# Always attempt to read the body; request.text() returns "" if empty
67+
text = await request.text()
68+
base_result["json"] = json_loads(text) if text else {}
6669
else:
6770
base_result["data"] = await request.post()
6871

tests/components/webhook/test_trigger.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from homeassistant.core import HomeAssistant, callback
99
from homeassistant.setup import async_setup_component
1010

11+
from tests.common import async_capture_events
1112
from tests.typing import ClientSessionGenerator
1213

1314

@@ -377,3 +378,46 @@ def store_event(event):
377378

378379
assert len(events) == 1
379380
assert events[0].data["hello"] == "yo world"
381+
382+
383+
async def test_webhook_query_json_header_no_payload(
384+
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
385+
) -> None:
386+
"""Test requests with application/json header but no payload."""
387+
events = async_capture_events(hass, "test_success")
388+
389+
assert await async_setup_component(
390+
hass,
391+
"automation",
392+
{
393+
"automation": {
394+
"trigger": {
395+
"platform": "webhook",
396+
"webhook_id": "no_payload_webhook",
397+
"local_only": True,
398+
"allowed_methods": ["GET", "POST"],
399+
},
400+
"action": {
401+
"event": "test_success",
402+
},
403+
}
404+
},
405+
)
406+
await hass.async_block_till_done()
407+
client = await hass_client_no_auth()
408+
409+
# GET
410+
response = await client.get(
411+
"/api/webhook/no_payload_webhook", headers={"Content-Type": "application/json"}
412+
)
413+
await hass.async_block_till_done()
414+
assert response.status == 200
415+
416+
# POST
417+
response = await client.post(
418+
"/api/webhook/no_payload_webhook", headers={"Content-Type": "application/json"}
419+
)
420+
await hass.async_block_till_done()
421+
assert response.status == 200
422+
423+
assert len(events) == 2

0 commit comments

Comments
 (0)