Sapling Logo
SDK authentication quickstart

Python JWT Generator

Sign a short-lived Sapling SDK credential in Python without exposing your private API key to browser code.

  • HS256 signature
  • Server-side only
  • Public + private keys
SIGN Python logo Python HS256 · sub + exp

Python JWT generator quickstart

Create a token with your public API key in the sub claim, a near-term Unix timestamp in exp, and an HS256 signature made with your private API key.

Sapling JWTs use HS256 with a sub claim containing your public API key and an exp claim containing a Unix timestamp. The examples use a one-hour lifetime; shorten it further when your application can refresh tokens easily.
Python HS256 · sub + exp

This example uses PyJWT.

import os
import time

import jwt

public_key = os.environ.get("SAPLING_PUBLIC_KEY")
private_key = os.environ.get("SAPLING_PRIVATE_KEY")
if not public_key or not private_key:
    raise RuntimeError("Set SAPLING_PUBLIC_KEY and SAPLING_PRIVATE_KEY first.")

token = jwt.encode(
    {
        "sub": public_key,
        "exp": int(time.time()) + 3600,
    },
    private_key,
    algorithm="HS256",
)

print(token)
Generated token text/plain
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.<base64url-claims>.<signature>

Return the compact token to the browser and pass it to Sapling.init as the key. Issue a fresh token after it expires; never send the private key.

About Python

Python is a high-level interpreted general-purpose scripting language that ranks as one of the most popular programming languages. It is designed to be readable and uses indentation as part of its syntax. The reference implementation, CPython is written in both C and Python, which provides the performance characteristics of C for computationally expensive number-crunching tasks.