PYTHON

Creating a Webhook Endpoint with Python Flask

Set up a simple webhook receiver endpoint using Python Flask to listen for and process incoming HTTP POST requests from third-party services, logging the payload.

from flask import Flask, request, jsonify
import json
import logging

app = Flask(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

@app.route('/webhook', methods=['POST'])
def webhook_receiver():
    """
    Receives and processes incoming webhook POST requests.
    """
    if request.method == 'POST':
        try:
            # Attempt to parse as JSON first
            if request.is_json:
                payload = request.get_json()
                logging.info(f"Received JSON webhook payload: {json.dumps(payload, indent=2)}")
            else:
                # Fallback for other content types, e.g., form data
                payload = request.get_data(as_text=True)
                logging.info(f"Received non-JSON webhook payload: {payload}")

            # Here you would add your custom logic to process the payload
            # e.g., save to database, trigger another action, etc.
            # process_webhook_payload(payload)

            return jsonify({"status": "success", "message": "Webhook received"}), 200
        except Exception as e:
            logging.error(f"Error processing webhook: {e}")
            return jsonify({"status": "error", "message": "Internal Server Error"}), 500
    else:
        return jsonify({"status": "error", "message": "Method Not Allowed"}), 405

if __name__ == '__main__':
    # For production, use a production-ready WSGI server like Gunicorn or uWSGI
    # Example: gunicorn -w 4 -b 0.0.0.0:5000 your_app_file:app
    app.run(debug=True, port=5000)
How it works: This Python Flask snippet demonstrates how to create a basic HTTP POST endpoint to act as a webhook receiver. It listens for incoming requests on the `/webhook` path, automatically parses JSON payloads if available, or captures raw data otherwise. The payload is logged, and the function returns a success response. This serves as a foundation for integrating with services that send data via webhooks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs