Automate Home Assistant with WebHooks

Firing automations in Home Assistant through external systems πŸš€ Let me show you how to do it!

Automate Home Assistant with WebHooks
Photo by Steve Johnson / Unsplash / Image / Image

If you use Home Assistant, you have usually already created many things or devices in Home Assistant. However, there are some use cases where you want to carry out automations (and corresponding actions) in Home Assistant, but these are not triggered by Home Assistant itself. This is where WebHooks come into play.

What are webhooks

In essence, webhooks are nothing more than API endpoints. You can find out exactly what API endpoints are in my introduction to REST APIs πŸ‘‡

Understanding and using REST APIs
APIs: Ubiquitous and everyone uses them , albeit directly. But what are they for and how do they work? We explain πŸ’‘

These defined endpoints are provided by systems, in this case Home Assistant, and (usually) expect a predefined structure.

So we can pass data to a system and feed the other system with data or indicate that an action has just been performed.

I myself use such a WebHook in n8n (I have already written an article on this) to send a notification to my cell phone via Home Assistant when I publish a new blog article. Since I plan many articles in advance, it's always nice to see that an article has been posted.

How are WebHooks defined in Home Assistant?

In Home Assistant, it's quite easy to define WebHooks. All we need to do is create a new automation and select "Webhook" as the entry point.

Each of these WebHooks is then given a fixed ID with which it can be accessed. With Home Assistant, the WebHooks are always specified as POST or PUT, so that data can also be transferred there. A GET would have the disadvantage that you can only deliver data via the query string.

This means that we could access our WebHook as follows:

POST https://homeassistant.local/api/webhook/-mNLpFGdHRSK0fhJIFDEOydyM

If we now fire the request with cURL, we will see our request in the automation processes:

If we also provide it with data as JSON in the body, we will also see this:

Transferring the data to the WebHook in Postman
Received data in Home Assistant

In the automation itself, we have our data in the trigger. In a Home Assistant template, we can access it with {{ trigger.json }}.

πŸ’‘
I will come back to how exactly this works with the templates in Home Assistant in a later article. At this point, however, I would like to refer you to the documentation on Templating.

We can then use this data to fire a notification in Home Assistant, for example:

service: notify.notify
data:
  title: Post published πŸ“‘
  message: "'{{ trigger.json.name }}' published"

And that's your first WebHook written and ready for use.

Cheers πŸ€™