# Request signature in Python 3

This article presents a sample implementation of a [request signature](../../developer-resources/security/request-signature.md) in Python 3.

<a id="dependencies">

## Dependencies

This example uses the [hmac](https://docs.python.org/3/library/hmac.html), [hashlib](https://docs.python.org/3/library/hashlib.html), [json](https://docs.python.org/3/library/json.html) and [urllib.parse](https://docs.python.org/3/library/urllib.parse.html) core dependencies from Python 3.

<a id="example">

## Example

The following simple example implements the algorithm described in the [Request signature](../../developer-resources/security/request-signature.md) 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}`

```py
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)
```

<a id="usage">

## Usage

Run:

```bash
python3 index.py
```

---

Full index of the Cloud Services documentation: [llms.txt](../../../llms.txt)
