Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
import hashlib
import hmac
import time
def sign_request(secret, method, path, body, timestamp=None):
timestamp = str(int(time.time()) if timestamp is None else timestamp)
message = b".".join([timestamp.encode(), method.upper().encode(), path.encode(), body])
signature = hmac.new(secret, message, hashlib.sha256).hexdigest()
return {"X-Timestamp": timestamp, "X-Signature": signature}
def verify_request(secret, method, path, body, headers, tolerance=300, now=None):
try:
timestamp = int(headers["X-Timestamp"])
supplied = headers["X-Signature"]
except (KeyError, ValueError):
return False
if abs((time.time() if now is None else now) - timestamp) > tolerance:
return False
expected = sign_request(secret, method, path, body, timestamp)["X-Signature"]
return hmac.compare_digest(expected, supplied)Example / expected output
headers = sign_request(b"secret", "POST", "/v1/orders", b'{"id": 1}')
verify_request(b"secret", "POST", "/v1/orders", b'{"id": 1}', headers) # TrueHow it works
The sender signs timestamp.method.path.body with a shared secret. The receiver recomputes the signature, compares it in constant time and rejects timestamps outside a small window, which stops replay of captured requests. Keep the secret out of source control and rotate it periodically.
Related snippets
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- JavaScript Tested
Generate secure random IDs and integers
Create UUIDs, random integers in a range and URL-safe tokens with the Web Crypto API instead of Math.random.
- PHP Tested
Generate a secure random token in PHP
Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.
- PHP Tested
Escape output to prevent XSS in PHP
A short helper around htmlspecialchars with the right flags for HTML text and attribute values.

