Skip to content

Make your first API request

Read your synced usage from a script. Personal API access is included in Free.

Before you start

Sign in to Tokematic on the web. Enable Tokematic sync on a computer that records your work and check that its sync completes. The API reads the records sent to your account.

This guide uses a personal credential. Organizations using project transport need project access with a supported account session or installation credential. External API credentials cannot read those project routes.

Create a read credential

  1. Open Credentials under Account settings.
  2. Create a credential with Personal as its owner. Select Read usage records.
  3. Save the credential in your secret store when it appears. It is shown once.
  4. Open Connection details on its row. Copy the Group prefix and check the API base URL.

Keep the credential out of source code and command history. A script sends it in the Authorization header using the Bearer scheme.

Read one page

Save this example as read_usage.py and run python3 read_usage.py. It uses Python's standard library. Enter your group prefix when prompted. The credential prompt hides what you type.

import getpass
import json
import urllib.error
import urllib.parse
import urllib.request

prefix = urllib.parse.quote(input("Group prefix: ").strip(), safe="")
credential = getpass.getpass("Tokematic API credential: ")
url = f"https://api.tokematic.app/v2/groups/{prefix}/records?type=UsageReport&limit=10"
request = urllib.request.Request(
    url, headers={"Authorization": f"Bearer {credential}"}
)
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        page = json.load(response)
    print(json.dumps(page, indent=2))
except urllib.error.HTTPError as error:
    print(f"Request returned HTTP {error.code}")
    print(error.read().decode("utf-8"))
except urllib.error.URLError:
    print("The API could not be reached. Check its status before retrying.")

The URL above uses production. Credentials from staging belong to https://api.stage.tokematic.app.

Check the response

A successful response contains records and next_cursor. An empty result looks like this:

{"records": [], "next_cursor": null}

An empty list means this query found no matching synced records. Check the credential's group and sync status. Protected fields remain encrypted.

For another page, send the returned next_cursor as cursor. Keep type=UsageReport on every request. Continue until next_cursor is null, even when a page contains fewer than ten rows. Scripts that pass structured filter arguments in JSON can also call QUERY /v2/groups/{prefix}/records with {"type": "UsageReport", "limit": 10, "cursor": "..."} and no URL query parameters.

Each record has its own version counter. since_version is a filter on those counters. To keep a local copy current, compare each record's name and version using select=index before fetching changed records.

Resolve a refused request

Response What to check
401 Use a current credential from this API environment.
403 Check Read usage records and the credential's group.
409 with migration_required Read the returned transport requirement. Organization project routes need a supported project credential.
429 Wait for Retry-After. Allowance failures also report reset windows.

Add session tags

Use a credential with Add tags to sessions when a script needs to change tags. The API guide explains how to find the provider and vendor session ID, set key/value fields and clear a field. A usage record ID is a different identifier.

End access

Choose Revoke on the credential's row when its script retires. Future requests fail. Downloaded copies stay where the script saved them.

Receive alert webhooks

Pro accounts can send alerts to their own systems. In Settings, Webhooks, choose Add webhook, enter an https address and copy the secret. It is shown once.

Each event is signed. Check the signature before you trust the body. Use the raw request body, not a parsed copy.

import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

export function verifyTokematicWebhook(secret: string, headers: Headers, rawBody: string): boolean {
  const id = headers.get("webhook-id");
  const timestamp = headers.get("webhook-timestamp");
  const signatures = headers.get("webhook-signature");
  if (!id || !timestamp || !signatures) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
  const expected = createHmac("sha256", secret).update(`${id}.${timestamp}.${rawBody}`).digest();
  return signatures.split(" ").some((candidate) => {
    const [version, value] = candidate.split(",");
    if (version !== "v1" || !value) return false;
    const given = Buffer.from(value, "base64");
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}

Answer with any 2xx status within 10 seconds. A failed delivery is retried for 3 days with the same webhook-id, so keep the ids you have handled and skip repeats. The body holds type (alert.raised, alert.updated or alert.resolved), timestamp and data with alert_id, topic, urgency, stage, title, detail and link. A resolved event carries the alert_id of the alert it closes.

To change a secret without losing events, choose New secret. For 24 hours each event carries a signature for both secrets, and the check above accepts either one. Send a test event from the same page.