This page covers the online validate call in Python and what to do with each answer. The token that makes the offline fallback possible is in offline verification in Python, the first-run call is in device activation in Python, and the docs have a shorter one-file version in the platform guides.
The client
The code needs only the standard library. It returns a Reply for any HTTP answer, including 4xx and 5xx, and None when there is no answer at all:
import json
import urllib.error
import urllib.request
from dataclasses import dataclass
BASE = "https://clavem.io"
@dataclass
class Reply:
status: int
body: dict
retry_after: float | None
def post(action: str, body: dict, *, base: str = BASE, timeout: float = 8) -> Reply | None:
request = urllib.request.Request(
f"{base}/v1/licenses/{action}",
data=json.dumps(body).encode(),
# Send your own User-Agent: some networks block the default Python one.
headers={"Content-Type": "application/json", "User-Agent": "Inkwell/3.2"},
)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
status, headers, raw = response.status, response.headers, response.read()
except urllib.error.HTTPError as error: # 4xx and 5xx still carry a JSON body and headers
status, headers, raw = error.code, error.headers, error.read()
except (urllib.error.URLError, TimeoutError, OSError):
return None # offline, DNS failure, timeout
try:
parsed = json.loads(raw)
except ValueError:
parsed = {}
retry = headers.get("Retry-After")
return Reply(status, parsed if isinstance(parsed, dict) else {}, float(retry) if retry and retry.isdigit() else None)
HTTPError is both an exception and a response object, which is why the 404 and 429 bodies are readable. URLError is a subclass of OSError, so the last except also covers socket errors. A timeout raises an OSError subclass too.
Turn the answer into an outcome
@dataclass
class Outcome:
kind: str # "valid" | "not-valid" | "unknown" | "no-answer"
token: str | None = None
reason: str | None = None
retry_after: float | None = None
def validate(key: str, instance_id: str | None = None, *, base: str = BASE) -> Outcome:
body = {"license_key": key, **({"instance_id": instance_id} if instance_id else {})}
reply = post("validate", body, base=base)
if reply is None:
return Outcome("no-answer")
if reply.status == 200 and isinstance(reply.body.get("valid"), bool):
kind = "valid" if reply.body["valid"] else "not-valid"
return Outcome(kind, token=reply.body.get("token"), reason=reply.body.get("error"))
if reply.status == 404:
return Outcome("unknown", reason=reply.body.get("error"))
if reply.status in (429, 503):
return Outcome("no-answer", retry_after=reply.retry_after)
return Outcome("no-answer") # 400 is a bug in the app; other 5xx is on the server
| Reply | Outcome | What the app does |
|---|---|---|
200, valid: true |
valid |
Save the new token. This restarts the 14-day window. |
200, valid: false |
not-valid |
Expired or disabled. Save the token, show reason, keep the key. |
| 404 | unknown |
Unknown key, or instance_id not found. Clear the license and ask for the key. |
| 429, 503 | no-answer |
No verdict. Use the saved token, retry later. |
| Timeout, no network | no-answer |
Same. |
Real output
The client against the live API with the public demo key, and a local stub for the limit cases:
demo key (live): {'kind': 'valid', 'token': 'sgt1.eyJ2Ijo...'}
unknown key (live): {'kind': 'unknown', 'reason': 'license_key not found.'}
demo key, unknown instance (live): {'kind': 'unknown', 'reason': 'instance_id not found.'}
empty body (live): 400 {'valid': False, 'error': 'license_key: Invalid input: expected string, received undefined'}
stub 429: {'kind': 'no-answer', 'retry_after': 60.0}
stub 503 with retry: {'kind': 'no-answer', 'retry_after': 5.0} after 5.0 s
stub expired: {'kind': 'not-valid', 'token': 'sgt1.eyJ2Ijo...', 'reason': 'This license key has expired.'}
slow server: {'kind': 'no-answer'} after 8.0 s
The 503 line shows one retry that waited the 5 seconds Retry-After asked for and then gave up. A 429 asks for 60 seconds, which is too long to hold a launch: use the saved token and try again later.
Keep the key in the keyring
import json
import keyring
from keyring.errors import KeyringError, PasswordDeleteError
SERVICE = "com.example.inkwell"
def load() -> dict | None:
try:
stored = keyring.get_password(SERVICE, "license")
except KeyringError: # no backend (headless Linux) or a locked keyring
return None
return json.loads(stored) if stored else None
def save(license: dict) -> None:
keyring.set_password(SERVICE, "license", json.dumps(license)) # raises NoKeyringError without a backend
def clear() -> None:
try:
keyring.delete_password(SERVICE, "license")
except (PasswordDeleteError, KeyringError):
pass
The roundtrip worked on macOS with keyring and the Keychain. The keyring README says Linux without a desktop needs a Secret Service, such as the GNOME Keyring daemon over D-Bus. A server or a container usually has none. save then raises NoKeyringError. Decide what that means for your product before you ship: refuse to run, or fall back to a file in the user’s config directory with 0600 permissions.
Pitfalls specific to Python
- No timeout by default.
urlopenwaits without limit unless you passtimeout=, andrequestsdoes the same.httpxhas a default of 5 seconds, which you can still tighten. A launch check without a timeout is a frozen app. - Do not block a GUI thread. In Tkinter or Qt, run the check in a worker thread. In asyncio code, call it with
asyncio.to_thread. - A frozen app needs a test run. After PyInstaller or Nuitka, run the built app once with the network off and confirm that
keyringstill finds its backend and that HTTPS works. Both are common failure points in frozen builds. - TLS on macOS. A Python from python.org may need its certificate step before HTTPS works. A call that fails only on some machines is usually this, and not the API.
- Keep the User-Agent. Some networks block the default
Python-urllibvalue.
Doing this with Clavem
The License API needs no secret, so nothing sensitive ships with your script or app. Plan limits never block validation. See the API reference for every field.
Questions
Should I use requests or urllib for license checks?
Either works, because the License API takes a plain JSON POST. urllib adds no dependency, which helps in a frozen app. requests or httpx are fine if you already ship them. Always pass a timeout, because urllib and requests have none by default.
Why does urllib raise an exception for a 404 from the License API?
urlopen raises HTTPError for every 4xx and 5xx status. HTTPError is also a response, so read its body with error.read() and its headers with error.headers to get the message and Retry-After.
Where should a Python desktop app keep a license key?
In the operating system's credential store through the keyring package. On a headless Linux server there is usually no backend, so handle the error and decide whether to refuse or to fall back to a file with strict permissions.