Request signature in Python 3
This article presents a sample implementation of a request signature in Python 3.
# Dependencies
This example uses the hmac and hashlib core dependencies from Python 3.
# Example
The following simple example implements the algorithm described in the Request signature guide. The most important thing is to use the hmac
module with the appropriate SHA256
algorithm and provide the parameters in the correct order: method
, url
, timestamp
, body
.
The method
parameter should be uppercase and url
should contain only the relative path from the URL, not the full URL address. The full URL address should be converted to e.g. /webhook?a=1
.
To verify the implemented request signature algorithm, you can use the data from the sample below. For the provided sample data, the correct request signature is 56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762
.
import hmac
import hashlib
API_SECRET = "SECRET"
def hmacDigest(data, key):
keyEncoded = key.encode()
dataEncoded = data.encode()
h = hmac.new(keyEncoded, dataEncoded, hashlib.sha256)
return h.hexdigest()
def generateSignature(method, path, timestamp, bodyString, secret):
methodUpperCase = method.upper()
data = methodUpperCase + path + timestamp
if (bodyString):
data += bodyString
return hmacDigest(data, secret)
method = "POST"
path = "/webhook?a=1"
bodyString = "{\"a\":1}"
timestamp = "1563276169752"
expectedSignature = "56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762"
signature = generateSignature(method, path, timestamp, bodyString, API_SECRET)
print(signature == expectedSignature)
# Usage
Run:
python3 index.py