navigation

Webhook with Spring Boot and H2 Database

Webhook with Spring Boot and H2 Database

by
August 29, 2017

What exactly is a webhook?

A webhook is one of the best ways for real-time communication with your application. Unlike typical APIs, a webhook delivers data to the applications which means that you get data immediately when it occurs. This makes it much more efficient for both provider and consumer. In the webhook you can register your URLs which it will target when the information is being streamed. A webhook makes a simple HTTP request to your app and you receive data.

Creating your own webhook

For an implementation I use a Spring Boot framework and I store my webhook in H2 database. H2 is an in-memory DB which is recreated every time we start the application. For H2 DB you can find more information here.

In my code I use two fields which I can identify the company with. The first one is a company name. Companies which use a webhook are separated by this field. And the second field is for the type of information which the app will consume. I have added the second field because а company can use particular services which are offered by a webhook.

There is a dto object which represents table from DB. The dto class contains four fields:

  1. ID
  2. URL
  3. company name
  4. type.

The URL is the callback which the logic calls when it has finished.
Company name and type:

DTO Code:

My repository is simple and extends a Crud Repository. I have also added two bonus methods for filtering information easily:

  1. The first one finds a webhook both by name and by type of service it has been registered with;
  2. The second one is only for company name.

Repository Code:

In my controller I have created оne simple method for adding a webhook. It’s a simple POST which consumes a webhook in JSON format. I have also attached services for deletion of registration (both by company and by type) and for updating a webhook.

Controller code:

And now that you have your own webhook let’s talk about where it is appropriate to use it. Here are my suggestions:

  1. When you want to extend your core product with others custom processes which communicate to your business logic in real-time.
  2. When you want to improve user experience and you have an application with asynchronous architecture.

And finally some things you should consider when building a webhook:

  1. Security! That is one of the most important things that you should consider. You can require the URL to use https.
  2. Carefully consider the data that you share .
  3. Think about a fallback mechanism in case of a problem with internet traffic. If you don’t have a fallback mechanism a webhook can’t be used in critical business operations.

Do you have experience on the topic? Feel free to share it in the comments.

Stoyan Ivanov

Java & Oracle Developer at Dreamix

More Posts - Website

Do you want more great blogs like this?

Subscribe for Dreamix Blog now!