> For the complete documentation index, see [llms.txt](https://k4k3ru.gitbook.io/k4k3ru-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://k4k3ru.gitbook.io/k4k3ru-docs/api/authentication/sign-request-with-python.md).

# Sign a Request with Python

Build an authenticated K4K3RU JSON-RPC request with Python. The standard library handles HMAC-SHA256; the `cryptography` package provides Ed25519 support.

## Prerequisites

* Python 3.10 or later.
* An API credential created with `hmac-sha256` or `ed25519`.
* `K4K3RU_API_KEY`, `K4K3RU_SECRET_KEY`, and `K4K3RU_SIGNATURE_ALGORITHM` set in your environment.

Install the Ed25519 dependency when you use an `ed25519` credential:

```bash
python -m pip install cryptography
```

## Example

Save this program as `sign_request.py`:

```python
import base64
import hashlib
import hmac
import json
import os
import secrets
import time


def base64url_decode(value: str) -> bytes:
    padding = "=" * (-len(value) % 4)
    return base64.urlsafe_b64decode(value + padding)


def base64url_encode(value: bytes) -> str:
    return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=")


def canonical_json(value: object) -> str:
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def sign(algorithm: str, secret: bytes, payload: bytes) -> bytes:
    if algorithm == "hmac-sha256":
        return hmac.new(secret, payload, hashlib.sha256).digest()
    if algorithm == "ed25519":
        if len(secret) != 64:
            raise ValueError(f"invalid Ed25519 private key length: {len(secret)}")
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

        return Ed25519PrivateKey.from_private_bytes(secret[:32]).sign(payload)
    raise ValueError(f"unsupported signature algorithm: {algorithm}")


api_key = os.environ["K4K3RU_API_KEY"]
secret = base64url_decode(os.environ["K4K3RU_SECRET_KEY"])
algorithm = os.environ["K4K3RU_SIGNATURE_ALGORITHM"]
method = "PaymentOnchain.CreateIntent"
params = {"productName": "usdc-base-mainnet-1"}
timestamp = int(time.time())
nonce = base64url_encode(secrets.token_bytes(16))
canonical_params = canonical_json(params)
payload = f"{method}\n{timestamp}\n{nonce}\n{canonical_params}".encode("utf-8")
signature = base64url_encode(sign(algorithm, secret, payload))

request = {
    "id": "1",
    "method": method,
    "params": params,
    "auth": {
        "apiKey": api_key,
        "timestamp": timestamp,
        "nonce": nonce,
        "signature": signature,
    },
}
print(json.dumps(request, indent=2, ensure_ascii=False))
```

Run it with:

```bash
python sign_request.py
```

The program prints a request body that you can send to `https://api.k4k3ru.com/` with `Content-Type: application/json`. Sign the same `params` value that you place in the request; do not independently modify or reparse it after signing.

## Next Steps

See [API Request Authentication](/k4k3ru-docs/api/authentication.md) for canonicalization, freshness, replay-protection, and troubleshooting requirements.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://k4k3ru.gitbook.io/k4k3ru-docs/api/authentication/sign-request-with-python.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
