Webhook basics and implementing in Java and SpringBoot

    Webhook basics and implementing in Java and SpringBoot

    14/08/2025

    Introduction

    Webhooks are a powerful mechanism for enabling real-time communication between different web applications. They are sometimes referred to as "reverse APIs" because they allow a server to send data to a client as soon as an event happens or after processing is complete, rather than the client having to repeatedly poll the server for updates.

    What are Webhooks?

    Webhooks are user-defined HTTP callbacks that allow one application to send real-time data to another whenever a specific event occurs. Instead of continuously polling an API for changes, a webhook lets the provider notify your application instantly by making an HTTP request (usually POST) to a URL you specify. This mechanism is widely used for integrating systems, automating workflows, and enabling event-driven architectures. For example, when a payment is completed or a code is pushed to a repository, the provider can immediately inform your app by sending a payload to your webhook endpoint.

    The Webhook Lifecycle

    • 1. Registration: The consumer application tells the provider (e.g., GitHub, Stripe) where to send webhook notifications by registering a public URL (the webhook endpoint).
    • 2. Event Occurs: An event happens in the provider system (e.g., a new commit is pushed, a payment is received, a user is created, etc.).
    • 3. Webhook Triggered: The provider immediately sends an HTTP POST request with event data (usually JSON) to the registered endpoint.
    • 4. Processing: The consumer webhook endpoint receives the POST request and processes the payload, updating its own state or triggering further actions.
    • 5. Response: The consumer webhook endpoint can optionally send a response back to the provider to acknowledge receipt of the webhook.

    This flow ensures your application reacts to external events as soon as they happen.


    Provider (e.g., GitHub, Stripe) Consumer (Your Java App) Event Occurs (e.g., push, payment) Webhook Endpoint /webhook 1. Event 2. Webhook POST 3. Process Registration: Consumer registers endpoint with Provider

    Implementing Webhooks in Java with Spring Boot

    Let's build a simple example with a provider that sends a webhook and a consumer that receives it.

    Project Setup

    Both the provider and consumer will be Spring Boot applications. You'll need the spring-boot-starter-web dependency for both.

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

    The Consumer Application

    The consumer application exposes an endpoint to receive webhook notifications.

    1. Create a record for the payload

    Let's create a record to represent the payload of the webhook.

    package com.example.consumer; public record WebhookPayload(String eventType, String message) { }

    2. Create the Webhook Endpoint

    The controller will receive the webhook message and process it. We are just logging the payload for now.

    package com.example.consumer; @RestController public class WebhookConsumerController { private static final Logger logger = LoggerFactory.getLogger(WebhookConsumerController.class); @PostMapping("/webhook-endpoint") public void handleWebhook(@RequestBody WebhookPayload payload, @RequestHeader Map<String, String> headers) { logger.info("Received a webhook!"); headers.forEach((key, value) -> logger.info("Header: {} = {}", key, value)); logger.info("Payload: {}", payload); // Process the event based on its type switch (payload.getEventType()) { case "user.created": logger.info("A new user was created: {}", payload.getMessage()); // Add logic to handle new user creation break; case "user.deleted": logger.info("A user was deleted: {}", payload.getMessage()); // Add logic to handle user deletion break; default: logger.warn("Received an unknown event type: {}", payload.getEventType()); break; } } }

    The Provider Application

    The provider application will send call the webhook endpoint of the consumer when something interesting happens.

    1. Create a Service to Send Webhooks

    This service will be responsible for sending the HTTP POST request to the consumer's webhook endpoint. We'll use Spring's RestClient to make the HTTP call.

    package com.example.provider; @Service public class WebhookProviderService { private final RestClient restClient = RestClient.create(); private final String consumerWebhookUrl = "http://localhost:8081/webhook-endpoint"; public void sendWebhook(String eventType, String message) { var payload = new WebhookPayload(eventType, message); try { restClient.post() .uri(consumerWebhookUrl) .body(payload) .retrieve() .toBodilessEntity(); System.out.println("Webhook sent successfully for event: " + eventType); } catch (Exception e) { System.err.println("Failed to send webhook for event: " + eventType + ". Error: " + e.getMessage()); } } }

    2. Create a Controller to Trigger Webhooks

    We'll create a simple controller in the provider application to simulate events that trigger webhooks.

    package com.example.provider; @RestController public class EventController { private final WebhookProviderService webhookService; public EventController(WebhookProviderService webhookService) { this.webhookService = webhookService; } @GetMapping("/trigger-create-event") public String triggerCreateEvent() { webhookService.sendWebhook("user.created", "A new user 'John Doe' was created."); return "'user.created' webhook sent!"; } @GetMapping("/trigger-delete-event") public String triggerDeleteEvent() { webhookService.sendWebhook("user.deleted", "User 'Jane Doe' was deleted."); return "'user.deleted' webhook sent!"; } }

    Here is how the flow works

    1. Start both applications. The consumer will listen on a port (e.g., 8081), and the provider on another (e.g., 8080).
    2. Trigger an event in the provider by accessing one of its endpoints (e.g., http://localhost:8080/trigger-create-event).
    3. The EventController in the provider calls the WebhookProviderService.
    4. The WebhookProviderService constructs an HTTP POST request with a JSON payload and sends it to the consumer's /webhook-endpoint URL.
    5. The WebhookConsumerController in the consumer application receives the request, deserializes the payload into a WebhookPayload object, and processes the event.
    6. You will see log messages in the consumer's console confirming that the webhook was received and processed.

    Conclusion

    Webhooks is a powerful pattern for building event-driven integrations between applications. With Spring Boot, creating both a webhook provider and a consumer is straightforward.

    For more in-depth tutorials on Java, Spring, and modern software development practices, follow me for more content:

    🔗 Blog 🔗 YouTube 🔗 LinkedIn 🔗 Medium 🔗 Github

    Stay tuned for more content on the latest in AI and software engineering!

    Summarise

    Transform Your Learning

    Get instant AI-powered summaries of YouTube videos and websites. Save time while enhancing your learning experience.

    Instant video summaries
    Smart insights extraction
    Channel tracking