0
0
Rest APIprogramming~5 mins

Why webhooks push notifications in Rest API

Choose your learning style9 modes available
Introduction

Webhooks push notifications to instantly tell your app when something important happens. This saves time and avoids checking repeatedly.

You want to get notified immediately when a user makes a purchase.
Your app needs to update data right after a change happens on another service.
You want to avoid asking a server for updates over and over again.
You want to trigger actions automatically when an event occurs elsewhere.
You want to keep your app in sync with external systems in real time.
Syntax
Rest API
POST /your-webhook-url HTTP/1.1
Host: yourserver.com
Content-Type: application/json

{
  "event": "event_name",
  "data": { ... }
}
Webhooks send data using HTTP POST requests to a URL you provide.
The data usually comes in JSON format describing the event.
Examples
This example shows a webhook notifying your server that a new order was created.
Rest API
POST /webhook/order HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "event": "order_created",
  "data": {
    "order_id": 1234,
    "amount": 50
  }
}
This webhook tells your app that a new user signed up.
Rest API
POST /webhook/user HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "event": "user_signed_up",
  "data": {
    "user_id": 5678,
    "email": "user@example.com"
  }
}
Sample Program

This simple Python program uses Flask to create a server that listens for webhook POST requests. When a webhook arrives, it prints the event name and data.

Rest API
from flask import Flask, request

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    event = request.json.get('event')
    data = request.json.get('data')
    print(f"Received event: {event}")
    print(f"Data: {data}")
    return 'OK', 200

if __name__ == '__main__':
    app.run(port=5000)
OutputSuccess
Important Notes

Webhooks are like a doorbell: they ring your app when something happens.

Make sure your webhook URL is secure and can handle incoming requests quickly.

Always respond with a success status to tell the sender you got the notification.

Summary

Webhooks push notifications to save time and resources by sending updates instantly.

They use HTTP POST requests to send event data to your app.

Use webhooks when you want real-time updates without asking repeatedly.