Skip to content

Verify a Webhook Signature in Python: Flask, FastAPI, Django

Verify HMAC-SHA256 webhook signatures in Python with hmac.compare_digest on the raw body. Copyable code for Flask, FastAPI, Django and AWS Lambda, plus a script that signs a test request.

By AyeWatch Team4 min read

Short answer: To verify a webhook signature in Python, compute hmac.new(secret, raw_body, hashlib.sha256).hexdigest() over the exact bytes you received, add the sha256= prefix and compare it with the signature header using hmac.compare_digest. Read the raw body before any JSON parsing; in Flask that is request.get_data() and in FastAPI await request.body().

One function for every framework

AyeWatch sends X-AyeWatch-Signature: sha256= plus the hex HMAC-SHA256 of the raw request body, keyed with your webhook secret. The check is the same in any Python framework; only the way you read the body and headers changes:

# ayewatch_signature.py
import hashlib
import hmac

def valid_signature(secret: str, raw_body: bytes, header: str) -> bool:
    expected = "sha256=" + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), (header or "").encode())

hmac.compare_digest takes the same time however many characters match, and returns False for different lengths rather than raising. Comparing bytes avoids the TypeError it raises for non-ASCII strings.

Don't hash re-serialized JSON. AyeWatch's body has no spaces between keys and values, while Python's json.dumps adds a space after each colon and comma, so json.dumps(request.json) never matches.

Flask and FastAPI

# Flask
import json
import os
from flask import Flask, request
from ayewatch_signature import valid_signature

app = Flask(__name__)
SECRET = os.environ["AYEWATCH_WEBHOOK_SECRET"]

@app.post("/ayewatch")
def ayewatch():
    raw = request.get_data()
    if not valid_signature(SECRET, raw, request.headers.get("X-AyeWatch-Signature", "")):
        return "bad signature", 401
    update = json.loads(raw)
    print(update["update_id"], update["topic_name"])
    return "", 200
# FastAPI
import json
import os
from fastapi import FastAPI, Request, Response
from ayewatch_signature import valid_signature

app = FastAPI()
SECRET = os.environ["AYEWATCH_WEBHOOK_SECRET"]

@app.post("/ayewatch")
async def ayewatch(request: Request):
    raw = await request.body()
    if not valid_signature(SECRET, raw, request.headers.get("x-ayewatch-signature", "")):
        return Response(status_code=401)
    update = json.loads(raw)
    print(update["update_id"], update["topic_name"])
    return Response(status_code=200)

In FastAPI, don't declare the body as a Pydantic model on this route; that parses it before you can hash it. Read request.body() and parse after the check.

Django and AWS Lambda

# Django view
import json
import os
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from ayewatch_signature import valid_signature

SECRET = os.environ["AYEWATCH_WEBHOOK_SECRET"]

@csrf_exempt
@require_POST
def ayewatch(request):
    if not valid_signature(SECRET, request.body, request.headers.get("X-AyeWatch-Signature", "")):
        return HttpResponse(status=401)
    update = json.loads(request.body)
    print(update["update_id"], update["topic_name"])
    return HttpResponse(status=200)
# AWS Lambda behind a function URL or API Gateway HTTP API
import base64
import json
import os
from ayewatch_signature import valid_signature

SECRET = os.environ["AYEWATCH_WEBHOOK_SECRET"]

def handler(event, context):
    body = event.get("body") or ""
    raw = base64.b64decode(body) if event.get("isBase64Encoded") else body.encode("utf-8")
    headers = {k.lower(): v for k, v in (event.get("headers") or {}).items()}
    if not valid_signature(SECRET, raw, headers.get("x-ayewatch-signature", "")):
        return {"statusCode": 401}
    update = json.loads(raw)
    print(update["update_id"], update["topic_name"])
    return {"statusCode": 200}

Django's CSRF check would reject the POST, so the view is exempt; the signature does that job. On Lambda, the body can arrive base64 encoded, and header names are lowercased, so the handler covers both.

Sign a test request

AyeWatch has no send-test button in the API, so sign a sample the same way it does and post it to your local server:

# send_test.py
import hashlib
import hmac
import json
import os
import requests

secret = os.environ["AYEWATCH_WEBHOOK_SECRET"]
payload = {
    "topic_id": 1,
    "topic_name": "Test monitor",
    "update_id": 1,
    "headline": "Test delivery",
    "content": "A signed test body.",
    "created_at": "2026-12-03T18:00:00Z",
}
raw = json.dumps(payload, separators=(",", ":")).encode()
signature = "sha256=" + hmac.new(secret.encode(), raw, hashlib.sha256).hexdigest()

resp = requests.post(
    "http://localhost:5000/ayewatch",
    data=raw,
    headers={"Content-Type": "application/json", "X-AyeWatch-Signature": signature},
    timeout=10,
)
print(resp.status_code)  # expect 200; change raw after signing and expect 401

Change the port to match your server: Flask defaults to 5000, uvicorn to 8000 and Django's runserver to 8000.

Keep a few unit tests next to the function so a refactor can't quietly break it. Run them with pytest:

# test_signature.py
import hashlib
import hmac
from ayewatch_signature import valid_signature

SECRET = "test-secret"
BODY = b'{"topic_id":1,"update_id":1}'

def sign(body):
    return "sha256=" + hmac.new(SECRET.encode(), body, hashlib.sha256).hexdigest()

def test_accepts_a_signed_body():
    assert valid_signature(SECRET, BODY, sign(BODY))

def test_rejects_a_changed_body():
    assert not valid_signature(SECRET, BODY + b" ", sign(BODY))

def test_rejects_the_wrong_secret():
    assert not valid_signature("other-secret", BODY, sign(BODY))

def test_rejects_a_missing_header():
    assert not valid_signature(SECRET, BODY, "")

What signature checks won't cover

  • Duplicates. A valid delivery can arrive twice when a retry follows a lost response. Dedupe on update_id; see webhook idempotency.
  • Replays. There is no timestamp header to check, so the update_id dedupe is also your replay guard.
  • Secret rotation gaps. POST /api/v1/webhook/rotate-secret switches to the new secret at once. Deliveries signed with the old one fail until your server has the new value, and they are retried.
  • Redirects. A 3xx answer fails the delivery with no retry. Register the final HTTPS URL.
  • A leaked secret. Keep it in an environment variable or your platform's secret manager, never in the repository. If you lose it, GET /api/v1/webhook returns it; if it leaks, rotate it.

Add verification to your receiver

  1. Save valid_signature in ayewatch_signature.py.
  2. Read the raw body in your framework's way and call valid_signature before parsing JSON.
  3. Return 401 on a bad signature and 2xx within 10 seconds on a good one.
  4. Run send_test.py and confirm a 200, then change the body after signing and confirm a 401.
  5. Register the URL with PUT /api/v1/webhook or in Notification settings, and store the secret from the response.
FrameworkRaw bodySignature header
Flaskrequest.get_data()request.headers.get("X-AyeWatch-Signature")
FastAPIawait request.body()request.headers.get("x-ayewatch-signature")
Djangorequest.bodyrequest.headers.get("X-AyeWatch-Signature")
AWS Lambdaevent["body"], base64-decoded if isBase64Encodedlowercased event["headers"]

Start a monitor in under a minute

Describe a topic or paste a URL. Cancel before the trial ends and you pay nothing.

Try it free for 7 days

The bottom line

Add valid_signature, run send_test.py for a 200 and a 401, and only then register the URL. A receiver that rejects forged bodies on day one never has to be patched in a hurry.

FAQ

How do I verify an HMAC SHA256 webhook in Python?

Compute hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest(), add any prefix the sender uses, and compare with the header using hmac.compare_digest.

Why does my Python webhook signature not match?

Most often the code hashed parsed and re-serialized JSON. Hash the raw bytes from request.get_data(), await request.body() or request.body instead.

Should I use == or hmac.compare_digest?

Use hmac.compare_digest. It takes constant time, so response timings don't reveal how much of a forged signature was right.

Where do I find my AyeWatch webhook secret?

PUT /api/v1/webhook and GET /api/v1/webhook return it as secret. POST /api/v1/webhook/rotate-secret replaces it at once.

Does AyeWatch sign webhooks with a timestamp?

No. The signature covers the body only. Store each update_id and skip repeats to guard against replays and retries.

verify webhook signature pythonpython hmac sha256 webhookhmac.compare_digestflask webhook signaturefastapi webhook raw body

Related articles