PYTHON
Creating a Simple Webhook Listener with Python Flask
Learn to set up a basic webhook endpoint using Python Flask to receive and process incoming POST requests with JSON payloads from external services.
from flask import Flask, request, jsonify
import json
import os
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook_receiver():
if request.method == 'POST':
try:
data = request.json
if data is None:
data = json.loads(request.data)
print(f"Received webhook payload: {json.dumps(data, indent=2)}")
if 'event_type' in data and data['event_type'] == 'order_created':
print(f"Order created event detected for order ID: {data.get('order_id')}")
return jsonify({"status": "success", "message": "Webhook received and processed"}), 200
except json.JSONDecodeError:
return jsonify({"status": "error", "message": "Invalid JSON payload"}), 400
except Exception as e:
print(f"Error processing webhook: {e}")
return jsonify({"status": "error", "message": str(e)}), 500
else:
return jsonify({"status": "error", "message": "Method Not Allowed"}), 405
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(debug=True, host='0.0.0.0', port=port)
How it works: This Flask snippet provides a basic implementation for a webhook receiver. It listens for POST requests on the `/webhook` endpoint, parses the incoming JSON payload, and includes example logic for processing specific event types. This is essential for integrating with services that send real-time notifications about events.