Skip to content

Python ​

This guide uses Python and requests to build the three tiles from the Recipes: due and overdue checks, completed against scheduled, and open actions. It then keeps a local copy of check instances in sync with updated_since. Each section below is part of one script; put them in a single file, in order.

You need Python 3.9 or later and an API key with hierarchy:read, checks:read and actions:read. See Getting Started.

sh
python -m pip install requests
export CONTINUAL_API_KEY='cntl_live_…'

Use a test key and export CONTINUAL_API_URL='https://staging.api.continualapp.com/public/v1' to run the script against staging.

Set Up a Session ​

python
import os
import time
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

import requests

BASE_URL = os.environ.get("CONTINUAL_API_URL", "https://api.continualapp.com/public/v1")

session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['CONTINUAL_API_KEY']}"


def get(path, **params):
    """GET a public API path, waiting out rate limits and timeouts."""
    for _ in range(5):
        response = session.get(f"{BASE_URL}{path}", params=params, timeout=30)
        if response.status_code in (429, 503):
            time.sleep(int(response.headers.get("Retry-After", "1")))
            continue
        response.raise_for_status()
        return response.json()
    response.raise_for_status()


def paginate(path, **params):
    """Yield every record of a list endpoint, following next_cursor."""
    params.setdefault("limit", 500)
    while True:
        page = get(path, **params)
        yield from page["data"]
        if page["next_cursor"] is None:
            return
        params["cursor"] = page["next_cursor"]


def summary(path, **params):
    return get(path, **params)["groups"]
  • The key is read from the environment, never written into the script.
  • get retries 429 (rate limited) and 503 (query timed out) after the Retry-After the API sends, and raises on any other error. Errors are problem documents: response.json()["detail"] explains what went wrong.
  • paginate requests 500 records a page, the maximum, and follows next_cursor until it is null, keeping the other filters unchanged.

Label Lines ​

Summaries return IDs. Fetch names once, including archived lines so that history still gets a label:

python
factories = {f["id"]: f for f in paginate("/factories")}
lines = {line["id"]: line["name"] for line in paginate("/lines", include_archived="true")}


def line_name(line_id):
    return lines.get(line_id, "(archived line)")

Tile 1: Due and Overdue Checks ​

Due now and overdue now need no time parameter: the summary's default range, instances due in the last 30 days, holds them unless a check's grace period is longer than about 23 days (then add a due_from further back). Missed today (checks that closed without a result) starts at the factory's local midnight, using the time zone on the factory record. All three are filtered to the same factory, so the counts describe the same lines:

python
factory = next(iter(factories.values()))
tz = ZoneInfo(factory["timezone"])
local_midnight = datetime.now(tz).replace(hour=0, minute=0, second=0, microsecond=0)

due_now = summary("/check-instances/summary", status="due", factory_id=factory["id"], group_by="line_id")
overdue_now = summary("/check-instances/summary", status="overdue", factory_id=factory["id"], group_by="line_id")
missed_today = summary(
    "/check-instances/summary",
    status="missed",
    origin="scheduled",
    check_kind="cil,centreline",
    include_archived="false",
    factory_id=factory["id"],
    due_from=local_midnight.isoformat(),
    group_by="line_id",
)

print("Due now / overdue now / missed today")
counts = {}
for key, groups in (("due", due_now), ("overdue", overdue_now), ("missed", missed_today)):
    for g in groups:
        counts.setdefault(g["line_id"], {"due": 0, "overdue": 0, "missed": 0})[key] = g["count"]
for line_id, c in counts.items():
    print(f"  {line_name(line_id)}: {c['due']} due, {c['overdue']} overdue, {c['missed']} missed")

The example uses your first factory, for both counts. For several factories, loop over factories and send each one's factory_id, with its own local midnight for the missed count. isoformat() includes the offset (for example 2026-10-17T00:00:00+11:00), which the API requires. requests URL-encodes the + for you.

Tile 2: Completed Against Scheduled ​

The portal's headline completion rate, per local day, for the last 30 days:

python
daily = summary(
    "/check-instances/summary",
    origin="scheduled",
    check_kind="cil,centreline",
    include_archived="false",
    factory_id=factory["id"],
    due_from=(local_midnight - timedelta(days=30)).isoformat(),
    group_by="due_date",
)

print("Completion rate by day")
for group in daily:
    rate = "—" if group["completion_rate"] is None else f"{group['completion_rate']:.1f}%"
    print(f"  {group['due_date']}: {rate} of {group['count']} scheduled")

completion_rate is null on a day with no completed or missed instances, so the code shows a dash rather than 0%.

Tile 3: Open Actions ​

Open actions, per line and category:

python
open_actions = summary("/actions/summary", status="open,pending_verification", group_by="line_id,category")

print("Open actions")
for group in open_actions:
    print(f"  {line_name(group['line_id'])} / {group['category'] or 'manual'}: {group['count']}")

Manual actions have a null category. Category is an open set, so print or group an unfamiliar value rather than dropping it.

Run It ​

sh
python continual_tiles.py
Due now / overdue now / missed today
  Juices: 8 due, 3 overdue, 31 missed
  Dairy: 11 due, 5 overdue, 41 missed
Completion rate by day
  2026-10-15: 94.2% of 520 scheduled
  2026-10-16: 91.7% of 304 scheduled
Open actions
  Dairy / defect: 10
  Dairy / deviation: 2
  Juices / manual: 2

Incremental Sync ​

To keep your own copy of records, for a data warehouse or a custom report, fetch everything once and then only what changed. Every list accepts updated_since, which returns records updated at or after that time, ordered by (updated_at, id).

python
def sync_check_instances(store, since):
    """Upsert changed check instances into `store`, and return the next `since`."""
    started = datetime.now(timezone.utc)
    for instance in paginate("/check-instances", updated_since=since.isoformat()):
        store[instance["id"]] = instance
    # Overlap the next window, because records can move while you page.
    return started - timedelta(minutes=5)


store = {}
since = sync_check_instances(store, datetime.now(timezone.utc) - timedelta(days=7))
print(f"Synced {len(store)} check instances; next sync from {since.isoformat()}")

Run sync_check_instances(store, since) on a schedule, saving since between runs. In a real integration, store is a database table keyed by id.

How this stays correct:

  • Upsert by id. The same record can arrive in more than one run; the latest copy wins.
  • Start the next window before this run began, with a few minutes' overlap. A record that changes while you page can move behind your cursor; the overlap picks it up next time.
  • Newly due work is included. A check instance's updated_at is the later of its last change and its due_at, so an instance appears in sync as soon as it becomes due, and again when it is completed or missed.
  • Nothing you've synced is deleted. Only future, never-visible instances are ever removed. You never need to delete records from your copy.
  • For the first full load, omit updated_since and page through everything. The busiest organisations raise about 75,000 instances a year, about 150 pages of 500.

The same pattern works for /actions, /factories, /lines and /machines. For the hierarchy, send include_archived=true so that archiving a line arrives as an update with status: "archived", rather than the line disappearing from the list.