File size: 913 Bytes
d55322d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import os, time, hashlib, hmac, requests

API_URL = os.environ["CHAPTLY_API_URL"]
API_SECRET = os.environ["CHAPTLY_API_SECRET"]
API_KEY = os.environ["API_KEYS"]  # optional, only if using ApiKeyMiddleware

def signed_request(method: str, path: str, json_payload: dict | None = None):
    body_bytes = (json.dumps(json_payload or {}) ).encode("utf-8")
    body_hash = hashlib.sha256(body_bytes).hexdigest()
    timestamp = str(int(time.time()))
    canonical = "\n".join([method.upper(), path, body_hash, timestamp])
    signature = hmac.new(API_SECRET.encode(), canonical.encode(), hashlib.sha256).hexdigest()

    headers = {
        "X-Timestamp": timestamp,
        "X-Signature": signature,
    }
    if API_KEY:
        headers["X-API-Key"] = API_KEY

    url = f"{API_URL}{path}"
    resp = requests.request(method, url, json=json_payload, headers=headers)
    resp.raise_for_status()
    return resp.json()