NEWCKEditor AI is here!
Sign up (with export icon)

Request signature in Python 3

Show the table of contents

This article presents a sample implementation of a request signature in Python 3.

Dependencies

Copy link

This example uses the hmac, hashlib, json and urllib.parse core dependencies from Python 3.

Example

Copy link

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 path should contain only the relative path and query parameters from the URL, not the full URL address. The full URL address should be converted to e.g. /webhook?a=1.

If the algorithm works correctly, it should generate the same signature as the one given below: 56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762 for the following parameters:

  • apiSecret=SECRET

  • method=POST

  • uri=http://demo.example.com/webhook?a=1

  • timestamp=1563276169752

  • body={a:1}

import hmac
import hashlib
import json
import urllib.parse
def hmacDigest(data, key):
 keyEncoded = key.encode()
 dataEncoded = data.encode()
 h = hmac.new(keyEncoded, dataEncoded, hashlib.sha256)
 return h.hexdigest()
def generateSignature(apiSecret, method, uri, timestamp, body):
 url = urllib.parse.urlparse(uri)
 path = url.path
 if (url.query):
 path = path + "?" + url.query
 methodUpperCase = method.upper()
 data = methodUpperCase + path + str(timestamp)
 if (body):
 data += json.dumps(body, separators=(',',':'), ensure_ascii=False)
 return hmacDigest(data, apiSecret)
expectedSignature = "56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762"
generatedSignature = generateSignature(
 "SECRET",
 "POST",
 "http://demo.example.com/webhook?a=1",
 1563276169752,
 {"a": 1}
)
print(generatedSignature == expectedSignature)
Copy code

Usage

Copy link

Run:

python3 index.py
Copy code

Was this page helpful?

Every day, we work hard to keep our documentation complete. Have you spotted outdated information? Is something missing? Please report it via our contact form.

© 2003 - 2026  CKSource. All rights reserved.

AltStyle によって変換されたページ (->オリジナル) /