Webhooks Tutorial: Receive and Verify Them in Python

Quick answer
A webhook is an HTTP request a service sends your server when something happens, instead of your server asking for updates. Your server exposes a URL, the sender posts JSON to it, and your code acts on the event. This post builds a receiver in Python using only the standard library, verifies the sender with an HMAC signature, and fixes the 401 mismatch most first attempts hit.
A clothing shop in Karachi takes orders on WhatsApp and is paid through a link. The payment provider knows the moment an order is paid, but the shop does not: someone must check the dashboard and message the customer. That gap leaves orders unconfirmed and customers chasing their parcel, and the shop loses a sale it already made. A webhook closes it. The provider posts an "order paid" event the second the money lands, and the server marks the order paid. No polling, no dashboard watching, no missed payment. This post builds that receiver in plain Python and shows how to prove the event really came from the provider.
What I would check before using it
My first check: does the shop need events pushed to it, or would a status check do? If it only needs to know whether one order is paid, querying the provider API when asked is simpler, as the Build Your First REST API post shows. Webhooks earn their keep when the shop must react the moment something happens, without asking first.
My second check: can the sender prove who it is? A public URL that acts on any POST is an open door: anyone who finds it can fake an "order paid" event and get goods for free. The receiver must verify a signature on every request with a shared secret. If the provider offers no signing, I would not trust its webhooks for payments.
My third check: what happens when my server is down? Providers retry for hours or a day, but a receiver that crashes loses the event once retries run out. Answer 200 only after storing the event, and return an error for anything unhandled, so the sender retries.
My fourth check: can I replay an event? Without a replay button, debugging means waiting for a real customer to pay again. A good provider resends past events from its dashboard, and I can replay one with curl, as this post does.
My verdict, as judgement: use webhooks when the shop must react instantly to events it does not control, the sender signs every request, and the receiver stores the event before acknowledging. It flips when a status check would do, the sender cannot sign, or the receiver cannot survive a restart.
A Karachi shop, receiving its first webhook
The demo is the Karachi clothing shop from the intro: a customer pays Rs 2,450 for order ORD-1042, and the provider posts an "order paid" event to it.
The receiver is one file, receiver.py, built on Python's http.server. It reads the raw body, checks the X-Signature header against the shared secret, and logs the order only on a match. The secret is a throwaway test value: in production it lives in an environment variable, never in the code.
import hashlib
import hmac
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = b"test-secret-123" # throwaway test secret, never a real one
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path != "/webhook":
self.send_response(404)
self.end_headers()
self.wfile.write(b"not found")
return
length = int(self.headers.get("Content-Length", 0))
raw_body = self.rfile.read(length)
received = self.headers.get("X-Signature", "")
# Sign the exact raw bytes, not a re-serialised copy.
expected = "sha256=" + hmac.new(
SECRET, raw_body, hashlib.sha256
).hexdigest()
if not hmac.compare_digest(received, expected):
print(
"SIGNATURE MISMATCH: received=%s expected=%s"
% (received, expected)
)
self.send_response(401)
self.end_headers()
self.wfile.write(b"signature mismatch")
return
parsed = json.loads(raw_body)
print(
"ORDER PAID: order_id=%s amount=%s city=%s"
% (parsed["order_id"], parsed["amount"], parsed["city"])
)
self.send_response(200)
self.end_headers()
self.wfile.write(b"ok")
def log_message(self, fmt, *args):
pass
if __name__ == "__main__":
print("Listening on http://localhost:8000/webhook")
HTTPServer(("127.0.0.1", 8000), Handler).serve_forever()
The sender signs the exact bytes it posts and sends them with curl. The signature is HMAC-SHA256 over the raw body. The payload is one order: ORD-1042, Rs 2,450, Karachi.
import hashlib
import hmac
import subprocess
import sys
SECRET = b"test-secret-123" # throwaway test secret, never a real one
body = b'{"order_id":"ORD-1042","amount":2450,"city":"Karachi","event":"order.paid"}'
sig = "sha256=" + hmac.new(SECRET, body, hashlib.sha256).hexdigest()
print("sending signature:", sig)
result = subprocess.run(
[
"curl", "-s", "-v", "-X", "POST", "http://localhost:8000/webhook",
"-H", "Content-Type: application/json",
"-H", "X-Signature: " + sig,
"--data-binary", "@-",
],
input=body, capture_output=True,
)
sys.stdout.write(result.stdout.decode(errors="replace"))
sys.stderr.write(result.stderr.decode(errors="replace"))
$ python3 --version
Python 3.12.3
$ python3 -u receiver.py
Listening on http://localhost:8000/webhook
The first attempt failed. The original receiver parsed the JSON and re-serialised it with json.dumps before computing the signature. The sender signed compact JSON with no spaces, but json.dumps adds spaces, so the receiver computed a different digest. The log shows both values:
$ python3 send_webhook.py
sending signature: sha256=0a5a2070188abe3a8b134212abe8c6bf41a097c8192fce9b25a859b2de444d59
> POST /webhook HTTP/1.1
> X-Signature: sha256=0a5a2070188abe3a8b134212abe8c6bf41a097c8192fce9b25a859b2de444d59
< HTTP/1.0 401 Unauthorized
signature mismatch
SIGNATURE MISMATCH: received=sha256=0a5a2070188abe3a8b134212abe8c6bf41a097c8192fce9b25a859b2de444d59 expected=sha256=4df670a6b61c649cf0b059b5f0511f7d8676312fe9c60081b4f0bc4aaa83e63d
The fix is one line: compute the signature over the exact raw bytes, the same bytes the sender signed, and parse the JSON only after the check passes. The retry then succeeds:
$ python3 send_webhook.py
sending signature: sha256=0a5a2070188abe3a8b134212abe8c6bf41a097c8192fce9b25a859b2de444d59
> POST /webhook HTTP/1.1
> X-Signature: sha256=0a5a2070188abe3a8b134212abe8c6bf41a097c8192fce9b25a859b2de444d59
< HTTP/1.0 200 OK
ok
ORDER PAID: order_id=ORD-1042 amount=2450 city=Karachi
Two more checks: no signature returns HTTP 401, and the wrong path returns HTTP 404. The shop now accepts only signed events at the right URL.
Common mistakes and how to fix them
First, verifying the signature over re-serialised JSON. The symptom is HTTP 401 with a server log showing two different digests. The fix: compute the HMAC over the exact raw request bytes, and parse the JSON only after the signature checks out.
Second, comparing signatures with == instead of hmac.compare_digest. The symptom is nothing at all: a plain == leaks timing information that lets an attacker guess the signature. The fix: always use hmac.compare_digest, which compares in constant time.
Third, returning 200 before storing the event. The symptom is a lost order: the server answers success, then crashes before saving, and the sender never retries. The fix: store the event first, then answer 200.
Fourth, putting the secret in the code or in a log line. The symptom is a secret that ends up in a git repo or a log file, where anyone who finds it can forge events. The fix: read the secret from an environment variable, and log only the order id and amount.
Frequently Asked Questions
What is the difference between a webhook and an API? An API waits for you to ask: your code sends a request and gets a reply. A webhook is the reverse: the service sends your server a request when something happens, so your code reacts instead of polling. Use an API to fetch data on demand, a webhook to react to events.
What happens if my server is down when a webhook arrives? Most providers retry for hours or a day, then give up. Answer 200 only after storing the event, and return an error for anything unhandled, so the sender retries.
Do I need a framework to receive webhooks? No. This post uses only Python's standard library http.server. A framework such as FastAPI, covered in the FastAPI post, helps as the receiver grows into a full API.
Can I trust a webhook just because it reached my URL? No. Anyone who guesses the URL can post to it, so the URL alone proves nothing. Trust comes from the signature: verify the HMAC on every request, and reject anything unsigned with 401.
What to remember
- A webhook is a POST your server receives when an event happens, so it reacts instead of polling.
- Verify the HMAC over the exact raw request bytes, never over re-serialised JSON.
- Compare signatures with
hmac.compare_digest, not==. - Store the event before answering 200.
- Keep the secret in an environment variable, never in code.
Where this leaves you
The shop no longer waits on a dashboard: the moment a customer pays, the provider posts the event, the receiver checks the signature, and the order is logged. The lesson that cost the most time was the quietest one: the bytes you sign and the bytes you verify must be the same bytes, not an equivalent copy. Build the receiver above, send it a signed event with curl, break the signature on purpose to watch the 401, and trust it the first time a real payment lands.
Further reading
- Stripe: Receive webhooks
- Python: http.server, HTTP servers
- GitHub: Validating webhook deliveries
- Build Your First REST API With Node.js and Express
- FastAPI Explained: Python APIs at Full Speed
- Postman Explained: Testing APIs Before the Frontend Exists
- Socket.IO Tutorial: Real-Time Order Updates in Node.js
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Originally published at https://practicaldevblog.blogspot.com/2026/12/webhooks-tutorial-python.html
Comments
Join the discussionNo comments yet. Be the first to comment.





