Webhook Trigger
The webhook trigger enables you to execute actions when a webhook is called in Home Assistant. It implements the same functionality as the Home Assistant webhook trigger, providing a seamless integration between SmartBeans and Home Assistant.
Annotating Methods
The @OnWebhookTrigger
annotation allows you to invoke any SmartBean method when the webhook is called.
public class ASampleBean implements SmartBean {
private SmartBeans sb;
@OnWebhookTrigger(id = "my_hook_id")
public void myWebhookCalled() {
sb.log("Webhook called.");
}
}
HTTP Methods
The webhook endpoint is automatically created by Home Assistant, when the trigger is registered. You can specify the HTTP methods that are allowed to call the endpoint.
public class ASampleBean implements SmartBean {
private SmartBeans sb;
@OnWebhookTrigger(id = "my_hook_id", allowedMethods = {Method.POST, Method.GET})
public void myWebhookCalled() {
sb.log("Webhook called.");
}
}
Webhook Events
Your annotated method can optionally include a WebhookEvent
parameter. When the trigger is fired, SmartBeans provides an
event object that gives you access to the event parameters. Through this object, you can retrieve the called webhook ID and
payload.
Payloads are exclusively accepted in JSON format. You can use the getPayloadAsObject()
method to directly access the
deserialized JSON data as a structured object.
public class ASampleBean implements SmartBean {
@OnWebhookTrigger(id = "my_hook_id", allowedMethods = {Method.POST, Method.GET})
public void myWebhookCalled(WebhookEvent event) {
event.getPayloadAsObject().asString("attribute");
}
}
Register Triggers Programmatically
As an alternative to the annotation-based approach, you can register triggers programmatically using the
registerTrigger()
method of the SmartBeans
API. To register a webhook trigger, you can use the webhook()
factory method of the Triggers
class. This factory provides a fluent API to create the same triggers as with
annotations. There are two main reasons to choose the programmatic approach over annotations:
- You need to create triggers with dynamic parameters, for example when the webhook ID is generated by business logic.
- You need to register or unregister the trigger at a specific point in time, rather than having it permanently active.
Here is an example of registering and unregistering a trigger with the programmatic approach:
public class ASampleBean implements SmartBean {
private SmartBeans sb;
private TriggerRegistration<WebhookEvent> webhookTriggerRegistration;
public void registerWebhookTrigger() {
webhookTriggerRegistration = sb.registerTrigger(
Triggers.webhook("my-webhook")
.withAllowedMethods(Method.PUT)
);
webhookTriggerRegistration.onTrigger(this::onWebhookCall);
}
public void unregisterWebhookTrigger() {
webhookTriggerRegistration.unregister();
}
private void onWebhookCall(WebhookEvent event) {
sb.log("Webhook called: " + event.getWebhookId());
}
}