[API polling VS webhook notifications](#api-polling-vs-webhook-notifications)
[Notification endpoints](#notification-endpoints)
[Handling notifications](#handling-notifications)
[The importance of asynchronous processing](#the-importance-of-asynchronous-processing)
[Notification payload](#notification-payload)
[Example](#example)

---

!!! About webhooks
API Integration with webhook notifications is a way to retrieve new data when an event occurs (i.e., a change has been made). Not only are webhooks significantly more efficient than API Pull Requests, they're an essential complement to API-based application integration because they free up time and resources on both sides.
!!!

---

## API polling VS webhook notifications

The main difference is that APIs send requests to get responses, whereas webhooks automatically send the responses without the need for any request.

While an API Pull Request would send a request for new events at a predetermined frequency and wait for the endpoint to respond (*aka* polling), webhooks automatically notify you in real-time when certain events occur (e.g., data has been modified - either its a creation, an update or a deletion).

**API Polling**

Imagine a character (representing a customer or an application) looking at his watch and regularly coming to a door (representing an API) to ask if there is any new data.
It's a repetitive process where the character keeps coming back, even though nothing has changed.

**Webhook Notifications**

Now imagine a doorbell or bell. Instead of the character regularly coming to the door, the door (the API) rings the bell or activates the doorbell to notify the character as soon as there is new data.
This is more efficient because the character doesn't need to check constantly. He simply waits to be notified.

The goal of **Quable Webhook Notification Service** is to alert your application whenever a change has been made to your Quable PIM data.

![Webhook vs API calls schema. The API regurlary sends requests to check for changes, whereas the webhook signals a change when it occurs](/static/images/webhooks.png "Webhooks")

---

## Notification endpoints

Webhook notifications are sent to dedicated URLs called **endpoints**. 
These endpoints are used when you subscribe to events. Once you've set up a subscription, notifications are sent in real-time to the designated endpoint when the event occurs.

!!!primary
Visit the page [Events](/webhooks/events/) to learn how to set up new webhooks from Quable PIM.
!!!

---

## Handling Notifications

Once you've set up subscriptions and are receiving notifications on events, the HTTP status code returned to Quable PIM API determines what happens next.

The Quable Webhook Notification Service sends its call to the designated endpoint and waits for a 200s HTTP response code (indicating success).

**Bad response from your service**
Any other response code will be considered as a failure and the notification will be retried.

**Response time too slow**
Any response longer than 5 seconds will be considered a failure and the notification will be retried.

**Automatic shutdown**
A maximum of two retries will be sent at five minutes intervals.
After the third consecutive failure (bad response / too slow), the webhook is **automatically disabled** and must be manually re-enabled.

!!!warning
The SSL certificate for the endpoint's domain must be valid.
!!!

---

## The importance of asynchronous processing

!!!warning 
Processing webhooks upon reception increases the risks of performance deterioration in case of heavy loads. We recommend to process webhook data asynchronously by storing the data in a queue instead of processing all incoming data at once. Specific libraries and tools are available to implement asynchronous processing depending on your system and setup.
!!!

Asynchronous processing is important for:

**Stability and Reliability** 
Direct processing of webhook notifications can jeopardize system stability. When faced with numerous or complex requests, servers may be overloaded, leading to slow responses or even outages. By queuing notifications for later processing, the load is evenly distributed, enhancing system stability and reliability.

**Traffic Peak Management** 
Webhooks can create significant traffic spikes, particularly during unforeseen events. Delayed processing allows your system to handle these surges without being overwhelmed, maintaining optimal performance under pressure.

**Enhanced Security**
Immediate processing of notifications can make your system more susceptible to attacks like Denial of Service (DoS). Deferred processing provides more time to verify request authenticity and implement appropriate security measures.

**Flexibility and Scalability**
Storing notifications for later processing offers the flexibility to manage data on your own terms and schedule. This approach adapts processing based on available resources, ensuring better scalability of your infrastructure.

**Resource Optimization** 
Deferred processing enables more efficient resource utilization. Instead of using resources for each individual notification, grouping and processing them together reduces costs and enhances overall efficiency.

---

## Notification payload

HTTP requests sent by **Quable Webhook Notification Service** is composed of a JSON Payload.
The structure of the notification payload is the same no matter the event you've subscribed to.

The following is a description of every item that can be included in a notification: 

| JSON Key                  | Description                                                   | Mandatory        |
|---------------------------|---------------------------------------------------------------|-------------------|
| `uuid`                    | The unique identifier of the event                            | Yes               |
| `code`                    | The event code (an event you've subscribed to.                | Yes               |
| `links`                   | The API address of the event.                                 | Yes               |
| `created_at`              | The date and time of the event.                               | Yes               |
| `created_by`              | The user who triggered the event.                             | Yes               |
| `resource`                | Information about the _updated_ entity.                       | Yes               |
| `resource.code`           | The unique identifier of the entity involved in the event.    | Yes               |
| `resource.type`           | The unique identifier of the entity type (i.e., asset, classification, document, link, predefined value, variant). | Yes |
| `resource.document_type_code` | The unique identifier of the document type.             | Yes (if `resource.type` = _"document"_) |
| `resources.links`         | API address to the updated entity (resource).              | Yes               |
| `locales.updated`         | The [locale]() used while updating the entity.             | Yes |
| `locales.inherited`       | An array of [locales]() impacted by an update. This array should be monitored because it uses inheritance. | Yes |
| `updated_items`           | An array of objects. Each object defines the exact item that has been updated.Possible items: asset (media), attribute (field), document, link, predefined value, variant (sku) | No |
| `process.correlationId`   |        A unique ID for Quable Services                                           |  Yes        |
| `process.id`              |        The unique ID of the process (import or bulk-edit)                        |  No         |
| `process.type`            |        If the event has been generated by a process, then this attribute will tell so :"import" "bulk_edit             |  No        |

---

## Example

```json
{
  "uuid": "ce6c64a3-4f27-4b0e-862c-ee780eae06d1",
  "code": "document.update",
  "links": [
    {
      "rel": "self",
      "href": "/events/ce6c64a3-4f27-4b0e-862c-ee780eae06d1"
    }
  ],
  "created_at": "2020-06-18T11:48:17+00:00",
  "created_by": "john_doe",
  "resource": {
    "code": "product_blue_pant",
    "type": "document",
    "document_type_code": "product",
    "links": [
      {
        "rel": "self",
        "href": "https://{{instance}}.quable.com/api/documents/product_blue_pant"
      }
    ],
    "locales": {
      "updated": [
        "fr_FR"
      ],
      "inherited": [
        "en_GB",
        "fr_FR"
      ]
    },
    "updated_items": [
      {
        "type": "field",
        "code": "color"
      },
      {
        "type": "field",
        "code": "name"
      }
    ]
  },
    "process": {
        "type": "bulk_edit",
        "id": "20aaabe5-5dcb-4cbb-80e8-ba75c30bbce0",
        "correlationId": "A4548C0354f48954x-565654qsds9chg564jhg78"
  }
}
```

---
