SafeWebhook/ Guides
Launch Workbench
FlaskPython

Python Flask Webhook Guide: request.get_data() & HMAC Signatures

Learn how to build secure webhook endpoints in Python Flask. Read raw request data with `request.get_data()` and verify Stripe & GitHub signatures.

Direct Answer / Quick Implementation Guide

In Flask, use `request.get_data()` to access the raw unparsed bytes before calling `request.get_json()`. Pass `request.get_data()` to your HMAC verification function to prevent signature errors.

Essential Implementation Takeaways

  • Access raw request bytes with `request.get_data()`.
  • Always use `hmac.compare_digest()` for timing-safe validation.
  • Return `jsonify({"received": True}), 200` to acknowledge delivery.
  • Use SafeWebhook to test Flask routes on localhost:5000.

Common Gotchas in Flask & How to Fix Them

Calling `request.json` before verifying signature
Fix:Access `request.get_data()` first for signature verification.

Complete Production Boilerplate

Python
# app.py (Flask Webhook Listener)
from flask import Flask, request, jsonify, abort
import hmac
import hashlib

app = Flask(__name__)
SECRET_KEY = b"your_signing_secret"

@app.route('/api/webhook', methods=['POST'])
def webhook_handler():
    raw_payload = request.get_data()
    sig_header = request.headers.get('X-Hub-Signature-256')

    if not sig_header:
        abort(400, description="Missing signature")

    computed_sig = 'sha256=' + hmac.new(SECRET_KEY, raw_payload, hashlib.sha256).hexdigest()

    if not hmac.compare_digest(sig_header, computed_sig):
        abort(401, description="Invalid signature")

    event = request.get_json()
    print(f"Received GitHub event: {event.get('action')}")

    return jsonify({"status": "received"}), 200

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

Step-by-Step Setup Guide

1
Import `Flask`, `request`, and `jsonify`.
2
Read raw payload bytes with `request.get_data()`.
3
Verify signature against `request.headers.get(...)`.
4
Parse JSON with `request.get_json()` after verification.
5
Return 200 OK.

How to Test Locally on Your Machine

  • Run `python app.py` (running on http://localhost:5000).
  • Use SafeWebhook Replay Drawer to replay captured events to `http://localhost:5000/api/webhook`.

Frequently Asked Questions: Flask Webhooks

Does Flask cache request.get_data()?

Yes, Flask caches the raw data stream so both `request.get_data()` and `request.get_json()` can be called in the same request lifecycle.

Test Your Flask Webhook Handler Live

Capture payloads, simulate errors, and replay directly to your localhost server.

Launch Webhook Workbench →

Explore Other Webhook Framework Guides