The ultimate guide to Contentful webhooks
Tags: webhooks, cms
Published: 2022-08-30 18:36:16

**NOTE**: This article originally appeared on the [Contentful Blog](https://www.contentful.com/blog/2022/08/25/ultimate-guide-contentful-webhooks/)

As web applications remain an integral and potent driving force of the digital age, developers, stakeholders, and end users can choose from a plethora of the newest technologies to support their applications. One of these tools is the webhook, which virtually any web app can integrate to create dynamic and responsive content. 

## What are webhooks?
Webhooks are a unidirectional mechanism that applications can use to talk to each other when a particular event occurs. Think of a webhook as an automated, one-way communication from one application to another. The first application sends the information to the receiver without waiting for a response. Then, it relies on the receiver to process this information. 

For example, you might use a content management system (CMS) platform to serve as a data source for your application. Ideally, when you update fields of the CMS and publish them, you want your application to know to look for these updates automatically. So, your CMS triggers a webhook that rebuilds the application to mirror the CMS.   

The one-way nature of webhooks differentiates them from many other communication systems, such as APIs. Though webhooks serve much of the same purpose as APIs, they’re less resource intensive and more efficient when you need to feed information somewhere asynchronously. 

APIs require both a request and a response, adding latency and possibly resulting in the need to poll for data with constant checks. In contrast, using webhooks eliminates the need to constantly check for new data. Instead, whenever a specific event occurs, the webhook automatically notifies you. Also, the one-way nature of webhooks enables multiple locations to receive the transmitted information simultaneously.

The use cases for webhooks primarily depend on what you want to achieve with your application. There are several ways you can use webhooks creatively to meet your goals. For example, with webhooks, you can listen for database changes for a user’s profile completion and then send an email to the user with welcome information, next steps, and so on. Additionally, you can integrate applications — such as Jira, Bitbucket, or a calendar application — with your messaging platform to enable receiving real-time updates. 

Now that you’re more familiar with the general idea behind webhooks, let’s explore how you can gain even more function and flexibility with Contentful webhooks.

## How Contentful webhooks work
The one-way communication webhooks provide is ideal for a system like Contentful. Contentful webhooks enable updates to flow in real time, as any change occurring within the system can trigger a webhook. The webhook then sends information about these changes or updates to any number of systems.

This low-latency architecture provides much faster communication than a similar API-driven system, ensuring that any change to content within the system is immediately reflected in all connected systems.

Most Contentful webhooks are triggered when either a data, content model, or content state undergoes a change. As a result, any sites or apps listening for that webhook then immediately know they need to update. These functionalities provide the possibility of triggering a chat event, an update event for users, or the rebuilding of your [Next.js](https://www.contentful.com/blog/2022/04/27/best-api-first-nextjs-cms/) or [Gatsby](https://www.contentful.com/blog/2022/05/31/the-best-cms-for-your-gatsby-project/) static website. 

Contentful webhooks can be divided into five type categories: ContentType, Entry, Asset, Task, and Release. Moreover, each type supports a variety of actions. For example, for an Entry webhook, Contentful supports all potential actions: create, save, auto_save, archive, unarchive, publish, unpublish, and delete.

The [table below](https://www.contentful.com/developers/docs/concepts/webhooks/) displays the capabilities of each webhook type:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1sjn5yjgl1zprl0vldfz.png)

In addition to the types mentioned in the table, Contentful also offers some proprietary webhooks for release actions, bulk actions, and scheduled actions. Let’s explore each one of these and how you can use them. 

### Release and release actions
To understand release actions, you first need to understand a release. A release is a field or tool that you can assign to your content. A primary application for a release might be to mass publish or unpublish the contents from your CMS. For example, if your ecommerce business is having a sales event and you want to publish all the spotlighted sale items, you can create and add the release to these items, then use it to publish and unpublish them. 

Release action webhooks can then listen for the release event — in this case, the publish and unpublish activities. Contentful supports two types of release actions: create and execute. The release action webhook is primarily designed to act on another action. For example, once you have published the release, you might want to listen for the release action webhooks. After successful execution, you might want to initiate a new website build to fetch data more efficiently. 

### Bulk actions
Bulk actions can be especially useful when the data your application displays to the end user is constantly changing, and your headless application needs to consistently remain updated to provide the best user experience. Similar to release action webhooks, Contentful supports create and execute actions with this bulk action webhook. 

Returning to the example of the hypothetical ecommerce site, assume you intend to provide discounts on certain products according to the day. For this situation, you can create bulk actions that publish new products at the end of each day and unpublish the previous day’s discounted items. 

By listening to bulk action webhooks, you are able to know precisely when the bulk action executes, and can then trigger a build accordingly. Therefore, this type of webhook is extremely beneficial for any site that displays frequently updated dynamic content. 

### Scheduled actions
Unlike bulk action and release action webhooks, scheduled actions expose webhooks for the create, save, execute, and delete event types. These webhooks can be beneficial for performing such steps as creating a build or running a search after setting up a scheduled action for your content. 

## Implementing webhooks
In this section, we’ll explain how to implement Contentful webhooks using both the Contentful dashboard and the Contentful API. 

### Using the Contentful dashboard
Contentful’s dashboard interface makes it easy to create webhooks, regardless of your level of expertise.  

Begin by logging into your account. Then, once you’re in the Space, click on the **Settings** dropdown on the upper navigation bar, as shown below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/his39gvw5l9sumu0tqmh.png)

After expanding the **Settings** dropdown, select **Webhooks** to navigate to the **Webhooks** dashboard.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ng62571d7chajmv4jfrv.png)

In the **Webhooks** dashboard, you’ll see a list of already created Webhooks (if you have any), a button labeled + **Add Webhook** toward the upper-right corner of the page, and a right-hand panel that displays another helpful Contentful feature: a selection of several Webhook template options. These templates provide a user-friendly way to create webhooks for your continuous integration/continuous deployment (CI/CD) integrations. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1zujjmdljbb24co2ui5.png)

For now, click the + **Add Webhook** button to open the form, as shown below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2z41qvkztvwogqqqf69w.png)

The form requires a name and URL for the webhook. Additionally, unless selected specifically, the created webhooks trigger all the events. 

Click the radio button next to **Select specific triggering events** to see the checkbox selections for the events and types that you want this webhook to listen to. The disabled checkboxes represent the events that Contentful does not support for the given action type. 

Then, after moving past the Triggers section, there’s an option to add filters to the webhook. It offers a variety of selections to compare, such as **Environment ID, Content Type ID, Entity ID, User ID(created by), User ID (updated by)**, and logical comparisons using equal, not equal, in, not in, regexp, and not regexp. Additionally, note that you can have more than one filter per webhook, which helps you to have sophisticated conditions. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4gxpr90iqmqnhl61ylrh.png)

After the **Filters**, you have the ability to set the **Headers, Content type, Content length, and Payload**. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6uk0d11s13jm216j1wh.png)

The **Payload** functionality provides the ability to alter the webhooks format to match your application’s structure. This can save considerable time. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m7jm8pyrgu5cd83zquim.png)

After filling in the necessary details, click **Save**. You’ve now created a webhook that you can view in the **Webhooks** dashboard. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0q0sm4uorg7zz2rgn5cr.png)

You now know how to create a webhook and add a filter using the Contentful graphical user interface (GUI). In the next section, you’ll use Contentful’s API to do the same.  

## Using the Contentful API to create the webhooks
Contentful also offers the API routes to create and configure the webhooks. But, before you continue using the APIs to retrieve the webhooks, ensure that you have the API key you need to authorize. 

You’ll start by fetching the list of existing webhooks. You can get the webhook you created using the GUI by executing a curl request. The only things that you’ll need are the `SPACE_ID` and `API_KEY`.  The curl request should appear as follows: 

```bash
curl -X GET "https://api.contentful.com/spaces/<SPACE_ID>/webhook_definitions"
-H "Authorization: Bearer <API_KEY>"
-H "Content-Type: application/vnd.contentful.management.v1+json"
```
Importing that request into Postman and pressing the Send button yields the previously created webhook with all the information, including the name, URL, space, filters, and headers. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyhccdtkml0ykjfltask.png)

Similarly, you can use the API to create the webhook. To create a webhook via the API, you’ll need the `SPACE_ID` and `API_KEY`. Here’s how a basic curl request looks: 

```bash
curl -X POST "https://api.contentful.com/spaces/<SPACE_ID>/webhook_definitions"
  -d '{"url": "<URL>", "name": "WEBHOOK_NAME", "topics": ["*.*"], , "filters": []}'
  -H 'Authorization: Bearer <API_KEY>'
  -H 'Content-Type: application/vnd.contentful.management.v1+json'
```
It accepts the four items as a part of the body of the API call, which includes URL, name, topics as an array of topics, and filters as an array of filters. 

Topics relate to what kind of changes you want to subscribe to (see the table at the beginning of the article). If you want to subscribe to all the actions across multiple types, you can use *.*. 

Similar to types and events, filters can also be passed in as a JSON object to the body of the API call to create the webhook. Check out what kind of filter constraints the API provides by reviewing the [official documentation](https://www.contentful.com/developers/docs/concepts/webhooks/). 

So, if you want a filter similar to the one you created using the GUI, you’ll need to pass the following `filters` object in the JSON body, like this: 

```json
 "filters": [
    {
      "in": [
        {
          "doc": "sys.environment.sys.id"
        },
        [
          "master"
        ]
      ]
    }
  ]
```
It’s also possible to add multiple logical conditions to behave like a logical “AND”: 

```json
"filters": [
    {
      "in": [
        {
          "doc": "sys.environment.sys.id"
        },
        [
          "master",
        ]
      ]
    },
    {
      "equals": [
        {
          "doc": "sys.id"
        },
        "146353"
      ]
    }
  ]
```
With the following information in mind, you can use the API with Postman. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3y4ogy9ithrq19ggiu49.png)

The following JSON object was passed to create a similar webhook as what you made using the GUI: 

```json
{
    "url": "https://www.example-app.com/api/update",
    "name": "Trigger Build API",
    "topics": [
        "*.*"
    ],
    "filters": [
        {
            "in": [
                {
                    "doc": "sys.environment.sys.id"
                },
                [
                    "master"
                ]
            ]
        }
    ]
}
```
After the successful request, you should get a similar response from the API: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xs3fjg8oxtz5snwy8ev6.png)

## Wrapping up
Contentful’s wide variety of webhooks can be largely beneficial for doing various tasks, such as building a static website after a set of actions, running a script to generate index files for the search, and sending a notification to the stakeholders after completion of scheduled or bulk actions.  

Contentful also offers two ways to create webhooks using the API and GUI, providing a balance of flexibility and function. [Sign up for a free Contentful account](https://www.contentful.com/sign-up/) and see how our market-leading content platform can support your project or business.