Steven Blanco
Oct 30, 2024

How to Build a Webhook Receiver with Flask

This article will walk you through how to set up Flask (a Python web development framework), create a webhook receiver, and test it.

In today’s interconnected digital world, data needs to flow freely between applications to support efficient, responsive systems. Enter webhooks—an essential tool in the developer’s toolkit for achieving seamless communication between services. A webhook is a simple HTTP request that’s triggered by specific events in a source system, allowing it to send data to another system automatically. By handling these events in real-time, webhooks make it possible for independent applications, like e-commerce platforms and payment gateways, to work together smoothly, eliminating the need for constant data polling and manual interventions.

To process these data streams, we need webhook receivers, which are endpoints or web applications configured to listen for incoming webhook requests from other systems. The receiver interprets the data in the webhook, performing actions based on its content—whether logging information, updating a database, or triggering downstream processes. Webhook receivers play a central role in integrated data systems, bridging the gap between platforms in a flexible and scalable way. This article demonstrates how to set up a basic webhook receiver in Python using Flask, a lightweight framework well-suited to this task. Python's readability, efficient performance, and extensive library ecosystem make it an ideal language for implementing webhooks, with Flask providing the tools to quickly create and test HTTP endpoints.

In this tutorial, we’ll walk through the steps of installing Flask, setting up a basic webhook receiver, and testing it with example data to ensure everything works as expected. First, we’ll cover how to initialize a Flask project and define a simple endpoint to capture webhook data. Next, we’ll explore ways to process and validate the incoming data securely, concluding with a brief overview of how to expand this setup for more advanced integrations. By the end, you’ll have a functioning webhook receiver in Python, ready to connect to external systems and handle incoming events in real time.

Install Flask

Before we begin building the webhook receiver, you'll need to have Python installed on your computer. If you haven't installed Python yet, you can download it here Next, install open your terminal and install Flask using pip. Flask is a python library that will allow us to set up a simple web server. Which is exactly what we need because a webhook is simply an HTTP post request which we can easily configure our Flask server to handle.

pip install Flask

With Flask installed, you're ready to start building your webhook receiver.

Build the Webhook Receiver

A webhook receiver listens for incoming HTTP requests triggered by external systems then process the data. Let’s create a basic Flask application that can receive and handle webhooks.

  1. Create a project directory named `webhook_demo`
  2. Create a file in `webhook_demo` named `receiver.py`
  3. Copy the code below and paste it in `receiver.py`
# Contents of receiver.py

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    if request.method == 'POST':
        data = request.json
        print(f"Received webhook data: {data}")
        process_data(data) # Process the webhook data here
        return jsonify({"message": "Webhook received!"}), 200
    else:
        return jsonify({"message": "Only POST requests are accepted!"}), 400
        
def process_data(data):
    # process data here
    pass

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)</code></pre>

Run this command in your terminal in the directory webhook_demo to start up the webhook server.

python3 receiver.py

Explanation of the Code

Importing Required Modules:

from flask import Flask, request, jsonify
  • request: This module allows us to only accept HTTP Post requests, which webhooks typically are
  • jsonify: This is used to send a JSON response back to the client

Initialize Flask application instance:

app = Flask(__name__)

Run the application:

app.run(debug=True, host='0.0.0.0', port=5000)

Defining the Webhook Route:

@app.route('/webhook', methods=['POST'])

This route decorator maps the /webhook URL to the webhook function. This means that when a client visits your webapp with the path "/webhook", your web server will start executing code inside the function that you mapped to /webhook, in our case process_data().

It instructs Flask to expect only POST requests at this endpoint, as webhooks typically use POST to send data. When a request is made to this URL, the code inside the webhook function will execute.

Handling Incoming Webhook Requests:

data = request.json
    print(f"Received webhook data: {data}")
    # Process the webhook data here
    return jsonify({"message": "Webhook received!"}), 200
  • if request.method == 'POST': This ensures that the route only handles POST requests, adding an extra layer of validation (even though the route is already restricted to POST).
  • request.json: this captures the JSON payload from the incoming request

Testing the Webhook Receiver

Once you’ve set up your webhook receiver, you’ll want to test it. First make sure its running then test it using the command below based on your operating system.

Linux/Mac OS X (via curl)

Run the following command in your terminal to send a POST request with a sample JSON payload:

curl -X POST http://localhost:5000/webhook \
    -H "Content-Type: application/json" -d '{"event": "order_created", "order_id": 12345, "customer": "John Doe"}'

Windows

For Windows, use the following command in PowerShell to send a POST request with a sample JSON payload:

Invoke-WebRequest -Method POST -Uri "http://localhost:5000/webhook" ` -ContentType "application/json" ` -Body '{"event":"order_created","order_id":12345,"customer":"John Doe"}'

Expected Output

If the webhook is working correctly, you’ll receive the following response:

{
"message": "Webhook received!"
}

Additionally, the JSON payload will be printed in your terminal where the Flask app is running.

Conclusion

In this article, we covered how to set up a Flask app, build a simple webhook receiver, and test it using curl. You can now expand this basic webhook receiver by adding more advanced logic, such as storing data in a database, triggering other API calls, or even sending email notifications.

Webhook receivers are a key part of many modern applications, allowing seamless communication between different services. With Flask, building and testing them is simple and efficient.

Steven Blanco Oct 30, 2024
More Articles by Steven Blanco

Loading

Unable to find related content

Comments

Loading
Unable to retrieve data due to an error
Retry
No results found
Back to All Comments