Sign up

tutorial

Webhooks Tutorial: Everything You Need to Know to Get Started with Webhooks

Angela Stringfellow

Last updated on

An application needs to communicate with other applications, servers, and users. There are different software tools and techniques to accomplish this. Application programming interfaces (APIs) are commonly used for such purposes. APIs are two-way communication systems and require more computing resources to maintain. Webhooks provide a simpler and less resource-intensive way to achieve some common information-sharing needs.

Let’s say you are a huge fan of the Boston Red Sox. You absolutely have to be in the office on a World Series game. You would love to know the scores in the game, but you cannot access the websites you’d need to visit from the office network. You just need to know the status of the number of home runs in the game, maybe because you made a small wager on the number of home runs.

Even if accessing the website or API was possible, you need to actively send requests to get the status of home runs. That means you’d have to check-in periodically to find out if the score has changed and who has hit the most recent home runs. This takes up bandwidth and computational power, and it’s not the best utilization of resources.

Imagine there was a way to get notified every time a home run is hit. You don’t need to monitor a website on a regular basis to keep tabs on the home run status. Instead, you can set up a webhook with the live score provider to push an HTTP request to your mail server. This can be further modified to send a premade template to forward the email to your email at work.

Definition of Webhooks

Webhooks are means of communicating automated messages between different applications. Messages are sent using HTTP protocol, and the communication is only in one direction. When two different applications have to work together, one of them will have to perform an action based on an event happening in the other application.

In the scenario given above, hitting a home run is the event. The change in the number of home runs in the database triggers an HTTP request to the mail server, which in turn sends an email. Multiple applications were able to relay information based on an event. The applications did not have to monitor constantly to check whether the event occurred.

With webhooks, the communication happens only in one direction and cannot be sent in the opposite direction. To send messages in both directions between two apps, APIs have to be used.

Webhooks vs. APIs

Due to the nature of webhooks, they are also called lightweight APIs. They are also sometimes referred to as reverse APIs. However, webhooks and APIs have many differences between them in spite of some similarities. Let’s take a look at some of the most important ways webhooks differ from APIs.

CRUD

APIs can be used to create, read, update and delete data from the API provider. Webhooks cannot manipulate data. They can only be used to read information.

Push vs. Pull

Actions performed with APIs require active effort from the user, and specific instruction has to be passed with the API. This can be considered a pull operation. On the other hand, webhooks trigger messages when an event occurs, which is a push operation.

Request vs. Events

APIs are request-based. This means the application or user that needs information has to send a request to the respective server according to the API standards. On the other hand, webhooks are event-based. When an event occurs a message is pushed out to the recipient, usually with HTTP protocol.

Resource Utilization

Implementing an API requires more resources. It uses more bandwidth and computing power to receive, process, and respond to the API calls. Also, to keep tabs on status changes with APIs, requests have to be sent constantly. Webhooks require relatively few resources, as HTTP messages are triggered only when the defined event occurs.

Communication Direction

APIs support two-way communication, meaning that two services connected with an API can talk to each other. On the other hand, webhooks only allow for one-way communication. The messages originate from the service at which the events occur and are sent to the service receiving the information.

Data Volume

Webhooks are typically used when the volume of data to be transmitted is small. Webhooks are generally not capable of handling large data volumes. APIs don’t have such limitations. Instead, the limitations on APIs are determined by the API provider’s infrastructure capability.

Real-time Data

When data is required in real-time, webhooks are a better solution as the messages are pushed out. APIs aren’t as useful for real-time information dissemination, because API calls have to be made regularly to receive real-time data. This can result in wasted resources and bandwidth.

How to Use Webhooks

Two applications can communicate with the help of webhooks. To make it possible, one of the applications has to accept a URL to send messages and the other application should be configured to receive the message. The messages have to be sent by the trigger application to the other application (action application) when triggered by an event.

The messages sent with webhooks are called requests, which are sent with HTTP protocol. The request has a well-defined structure that has four distinct parts:

  • URL: General web addresses are URLs. Users of the webhooks have to specify where to send messages. The location to send the messages to is passed as a URL. The user should pass a URL from where they can access information.
  • Body: The information to be sent is the body of the request, which is called the payload. The body can be sent in JSON or XML format instead of HTTP.
  • Header: The header specifies how the information in the payload is formatted. It provides context to the data.
  • Request method: The request method is the action to be taken by the application that receives the message. The HTTP methods used are GET, POST, PUT, and DELETE.

When the configured event is triggered, the trigger application sends associated data to the action application. Based on this, the action application has to perform the specified task (or action). The action application also needs to send back an HTTP status code to the trigger application as an acknowledgement. 302 is the HTTP code used to indicate the successful receipt of data, and 404 is used when there’s an error in receiving the message.

Take the home runs example we discussed previously. An email has to be sent when a home run is hit in the game. You can create a webhook with an application that provides live scores. As an example, say the URL of the application is baseball.com. The application is configured to send messages to your mail server. Let’s assume your URL to be yourapp.com.

In this example, the trigger application is baseball.com and the action application is yourapp.com. The event that triggers the webhook is a home run occurring in the game. The URL added to the webhook is https://yourapp.com/home-run-tracker/. When a home run occurs in the game, baseball.com sends a message to yourapp.com with the following URL:

https://yourapp.com/home-run-tracker/?NewHomeRun=1&HomeRunTeam=RedSox&TotalHomeRun=7&RedSoxHomeRun=4&YankeesHomeRun=3

The message contains the following information:

NewHomeRun=1     // A new home run is hit
HomeRunTeam=RedSox      // Team that hit the latest home run is Boston Red Sox
TotalHomeRun=7     // Total number of home runs in the game is seven
RedSoxHomeRun=4    // Total number of home runs hit by Boston Red Sox is four.
YankeesHomeRun=3     // Total number of home runs hit by New York Yankees is three.

When this message reaches the action application, it has to send a premade email to your work email address. The email can be a template and can be filled with the information received from the trigger application through webhooks.

Webhooks Examples

Webhooks are very commonly used in modern applications. In this section, we’ll review a couple of examples of webhook implementation.

Google Sheets Example

Google Sheets has a webhook integration that can be used by anyone without much coding experience. This is an example in which webhooks are used to trigger emails according to events in stock price movement. Webhooks can be used to track specific events related to the share price movement. Webhooks implementation with Google Sheets is abstracted away from the end user.

Let’s say we want to track the share price movement of Alphabet, the parent company of Google. First, you’d create a Google Sheet as shown in the image below:

Google Sheet screenshot
Create a Google Sheet

The current price of Alphabet stock can be obtained by the following function:

=GOOGLEFINANCE(“GOOG”)

The 52-week high of the share price can be obtained with the function:

=GOOGLEFINANCE(“GOOG”, “High52”)

The final column is a conditional statement with IF. The statement IF(B2< 0.5*C2, “YES”, “NO”) checks whether the share price of Alphabet has fallen to below half of the 52-week high.

Then select Tools > Script Editor from the Google Sheets menu.

Google Sheet menu dropdown screenshot
Select Tools > Script Editor

This brings up a window where custom scripts can be written. Paste the script given below:

function onEdit() {
  var emailAddress = 'youremail@gmail.com'; // insert your gmail id here
  // Send Alert Email.
  var message = 'Alphabet share price have fallen to half of its 52-week high'; // Second column
  var subject = 'Alphabet share alert';
  MailApp.sendEmail(emailAddress, subject, message);
}
Script Editor screenshot
Paste the script into the Script Editor

This function sends an email to your desired email ID with the subject and message as given in the code snippet. Save the script with the save button (in the shape of a disk) at the top of the window. Next, click on the button with the clock logo on the left-hand side of the window.

In the window that pops up, click on the “Add Trigger” button at the bottom right-hand side of the screen. The following pop up window appears:

"Add Trigger" popup screenshot
Click "Add Trigger"

In the first field, you’ll choose which function to run. It’s the onEdit function in the code snippet saved in the script editor. Choose “Head” for the deployment and “From Spreadsheet” as the event source. The event type is onEdit. Then hit “Save.” This triggers permission requests from Google. Grant the permissions to complete the creation of the webhook.

When the share price actually falls below half the 52-week high of the stock, cell D2 of the spreadsheet changes from “NO” to “YES.” This becomes an edit in the spreadsheet. This event triggers the function saved in the script editor to send an email to the email address given. The recipient receives an email that looks like this:

Recipient email screenshot
The recipient receives the above email

By using webhooks, you do not have to keep tracking the share price of the stock. When the event occurs, you’ll be alerted by email. If the Google Finance API had to be used instead of setting up a webhook like this, regular queries to the API would need to be sent to keep track of the share price. This simple webhook connecting Google Sheets to send emails can be used for different use cases.

Other Real-World Examples of Webhooks in Practice

E-commerce websites send regular emails while users are transacting with the site. Adding a product to their shopping cart, making a purchase, product movement with the logistics provider, etc. are all considered events. These events can trigger emails to the user. This can be accomplished by a webhook integration with the e-commerce platform and a transactional email provider. This automatically sends the appropriate transactional emails according to the events triggered.

One of the common two-factor authentication techniques used is a code provided as an SMS message. When a user tries to log in to a website by entering the login credential, it’s an event. This event triggers sending an SMS message to the user. This can be implemented by a webhook with the platform and a messaging service like Twilio. The action of sending the code is automated and happens based on a trigger event, which is the user entering the correct login credentials for the website.

Similarly, SMS messages and emails are sent for bank transactions. This can be implemented using webhooks. While you can also use email APIs to send transactional emails in this case, almost all transactional messaging can be implemented using webhooks.

One of the most popular webhooks integrations is with GitHub. When a code change is pushed to the GitHub repository, it can be used as an event to send notification messages to communication applications like Discord or Slack. This can be used to notify the developers to inspect and merge code.

Event-driven Automation

Many processes in software are dependent on other processes and events.

Using APIs to listen to events and accomplish an action is costly and consumes significant computing resources. Webhooks are lightweight solutions for performing event-driven tasks.

Webhooks are increasingly being used in modern application development, and more applications are adopting webhook support as a feature. This will help to simplify app-to-app communication and enable event-driven software process automation.

Notifications can take several forms, but they’re increasingly important in the modern world, as users rely on a growing number of websites and applications for many day-to-day tasks.

Whether you use APIs or webhooks to set up notifications, MagicBell’s complete notification system allows you to centralize and sync notifications, ensuring that users never miss important notifications while also ensuring that you don’t notify users twice on different platforms. Try it yourself.