Skip to content

Guides

Listing and syncing

Keep a dashboard or warehouse in step with your sessions using keyset pagination and updated_since.

Webhooks tell you about changes as they happen. Listing lets you build dashboards, backfill a new system and catch what a missed event left behind. This page also states the limits of that recovery.

Listing sessions

GET/v1/sessions

List sessions
curl -G https://api.aimedintake.com/v1/sessions \
  -H "Authorization: Bearer $AIMEDINTAKE_API_KEY" \
  -d updated_since=2027-01-12T00:00:00Z \
  -d status=completed \
  -d status=failed \
  -d limit=100
List parameters
ParameterRules
updated_sinceInclusive lower bound on updated_at.
statusReturn only sessions in this status. Repeat the parameter to match several.
external_refExact match on your reference: the way to find a session when you have lost its id. Cannot be combined with after.
limit1 to 200. Default 50.
afterThe next_cursor of the previous page.
Response · 200
{
  "data": [
    {
      "id": "ses_01JDK9W5RT",
      "object": "session",
      "external_ref": "visit-000479",
      "status": "failed",
      "mode": "intake",
      "language": "es",
      "device_type": "mobile",
      "tags": {},
      "created_at": "2027-01-12T11:40:00Z",
      "upload_expires_at": "2027-01-13T11:40:00Z",
      "accepted_at": "2027-01-12T11:52:18Z",
      "completed_at": null,
      "updated_at": "2027-01-12T12:01:44Z",
      "purge_at": "2027-02-11T11:52:18Z",
      "end_reason": "disconnected",
      "error": {
        "code": "pipeline_timeout"
      },
      "deleted": null
    },
    {
      "id": "ses_01JDK8Z3Q4",
      "object": "session",
      "external_ref": "visit-000481",
      "status": "completed",
      "mode": "intake",
      "language": "en",
      "device_type": "kiosk",
      "tags": {
        "site": "clinic-03"
      },
      "created_at": "2027-01-12T13:02:11Z",
      "upload_expires_at": "2027-01-13T13:02:11Z",
      "accepted_at": "2027-01-12T13:09:02Z",
      "completed_at": "2027-01-12T13:09:40Z",
      "updated_at": "2027-01-12T13:09:40Z",
      "purge_at": "2027-02-11T13:09:02Z",
      "end_reason": "normal_completion",
      "error": null,
      "deleted": null
    }
  ],
  "has_more": true,
  "next_cursor": "eyJ1IjoiMjAyNy0wMS0xMlQxMzowOTo0MFoiLCJpIjoic2VzXzAxSkRLOFozUTQifQ"
}

The list contains session objects only, never transcripts or results. It does include end_reason, and a value such as emergency says something about the person. Show that field only to staff who may see it, and fetch clinical content per session from the result endpoint.

Pagination

Lists are ordered by ascending (updated_at, id) and paged with a cursor. While has_more is true, pass next_cursor as after to get the next page.

  • The cursor is opaque. Do not build or modify it.
  • It is exclusive: the next page starts after the last item you received.
  • It is bound to the filters it was issued with. Changing status or updated_since between pages returns 422 cursor_mismatch.
  • Paging is by position in the ordering, not by offset, so pages stay stable and cheap however long the list grows.

Incremental sync

To keep a database or warehouse in step:

  1. Store a watermark: the latest updated_at of a run that finished without an error, kept as the exact string the API returned.
  2. On each run, list with updated_since set to the watermark minus two minutes, and page to the end.
  3. Upsert each session by id. For sessions that became completed, fetch the result.
  4. Save the new watermark only after the whole run has succeeded.
Incremental sync
# Requires Python 3.11 or later.
from timestamps import is_later, overlap_boundary  # shown below

import os
import requests

API = "https://api.aimedintake.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['AIMEDINTAKE_API_KEY']}"}


def problem_code(response):
    """The problem code, or the HTTP status when the body is not a problem document."""
    try:
        return response.json()["code"]
    except (ValueError, KeyError, TypeError):
        return f"http_{response.status_code}"


def sync(watermark):
    """Upsert every session changed since the watermark; return the new watermark.

    The watermark is an updated_at string exactly as the API returned it.
    Save the returned value only after this function returns without an error.
    """
    params = {"updated_since": overlap_boundary(watermark), "limit": 200}
    newest = watermark
    while True:
        response = requests.get(f"{API}/sessions", headers=HEADERS, params=params, timeout=30)
        if not response.ok:
            raise RuntimeError(f"List failed: {problem_code(response)}")
        page = response.json()
        for session in page["data"]:
            # Keyed by session["id"]; replace the stored row only if is_later(new, stored).
            upsert(session)
            if is_later(session["updated_at"], newest):
                newest = session["updated_at"]  # keep the original string, at full precision
        if not page["has_more"]:
            return newest
        params["after"] = page["next_cursor"]
Timestamp helpers
# Comparing API timestamps without losing precision. Written for Python 3.11 or later.
# A datetime keeps microseconds only, so the fractional part is compared as text.
# The API always answers in UTC with "Z"; an offset such as "+00:00" is accepted as well,
# and so are a lowercase "t" and "z", which RFC 3339 allows.
import re
from datetime import datetime, timedelta, timezone

RFC_3339 = re.compile(r"^(\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2})(?:\.(\d+))?([Zz]|[+-]\d{2}:\d{2})$")


def _parts(timestamp):
    """Split an RFC 3339 timestamp into its whole-second instant and its fractional digits."""
    match = RFC_3339.match(timestamp)
    if not match:
        raise ValueError(f"Not an RFC 3339 timestamp: {timestamp}")
    whole, fraction, zone = match.groups()
    # The zone belongs to the whole-second part; the fraction is the same in every zone.
    # Both separators are made uppercase before parsing.
    offset = "+00:00" if zone.upper() == "Z" else zone
    instant = datetime.fromisoformat(whole.upper() + offset).astimezone(timezone.utc)
    return instant, (fraction or "").rstrip("0")


def is_later(a, b):
    """True when a is a later instant than b, at any precision."""
    # Digit strings without trailing zeros order like the fractions they stand for.
    return _parts(a) > _parts(b)


def overlap_boundary(watermark, overlap_seconds=120):
    """The updated_since value for the next run: the watermark minus an overlap, rounded down to a second."""
    instant, _ = _parts(watermark)
    return (instant - timedelta(seconds=overlap_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
  • Overlap. The two-minute overlap re-reads the most recent changes on every run. It makes the sync insensitive to changes that were being written while the previous run finished. Your upsert makes the repeats harmless.
  • Compare instants, not strings, and lose no digits. Timestamps are RFC 3339, always in UTC with Z, and can carry fractional seconds. The helpers also accept an explicit offset such as +00:00, in case a value passes through a system that rewrites it. 12:00:00.100Z is later than 12:00:00Z but sorts before it as text. A native date type is not enough either: it rounds to milliseconds or microseconds, and two changes inside that step would look equal. The helpers compare whole seconds and then every fractional digit. Use them both to choose the newer of two rows and to advance the watermark, and store the original string. Only the updated_since boundary is rounded, downwards, which the overlap makes safe.
  • A result can be gone. Between listing a completed session and fetching its result, the session may be deleted or purged. Treat 410 from the result endpoint as a normal outcome.

updated_at advances on every change: transcript acceptance, completion, failure, expiry, deletion and purge. A sync every few minutes is ample, and a daily run is a sound safety net behind webhooks.

Tombstones

When a session’s clinical data is deleted from the API, by your request or at the end of the API’s retention period, the session stays visible as a tombstone for 90 days. For that time it appears in the list and can be read with GET /sessions/{id}; afterwards the session returns 404 not_found.

Tombstone
{
  "id": "ses_01JDK8Z3Q4",
  "object": "session",
  "external_ref": null,
  "status": "deleted",
  "mode": "intake",
  "language": "en",
  "device_type": "kiosk",
  "tags": {},
  "created_at": "2027-01-12T13:02:11Z",
  "upload_expires_at": "2027-01-13T13:02:11Z",
  "accepted_at": "2027-01-12T13:09:02Z",
  "completed_at": "2027-01-12T13:09:40Z",
  "updated_at": "2027-01-19T09:15:00Z",
  "purge_at": "2027-02-11T13:09:02Z",
  "end_reason": null,
  "error": null,
  "deleted": {
    "at": "2027-01-19T09:15:00Z",
    "reason": "erasure"
  }
}

A tombstone has status: "deleted", a deleted object with the time and reason, external_ref: null, empty tags and end_reason: null. What you do with it depends on the reason:

Handling a tombstone
deleted.reasonMeaningWhat to do
retentionThe API reached the end of its own retention period for this session.Mark the result as no longer available from the API, and drop any cache that only mirrors the API. This is not an instruction to delete your own records: keep them under your own retention policy.
erasureYour organization called DELETE for this session.Mark the result as unavailable from the API. Whether your own copy is erased is decided by your erasure process, which is normally what triggered the deletion in the first place.

Retention purges send no webhook, so listing is how you learn about them.

Recovery windows

Listing recovers missed changes, within limits that follow from retention:

Recovery windows
What you missedRecoverable until
A webhook eventWe retry for 72 hours. After that, a sync finds the change.
A resultThe session’s purge_at, or its deletion if that comes first. A result that was purged or deleted before you fetched it cannot be retrieved again.
A deletion or purgeThe tombstone is visible for 90 days.

If your sync has been stopped for longer than 90 days, tombstones may already be gone and an incremental sync cannot tell you about those sessions. Reconcile in full instead: list every session without updated_since, and treat any session you hold that is no longer listed as no longer available from the API.

Usage records

GET/v1/usage

Each completed session produces exactly one usage record, and only records with billable: true are charged. The endpoint lets you reconcile an invoice or attribute cost internally. It needs the usage:read scope. Usage records contain no transcript or result text and no end reason.

List usage
curl -G https://api.aimedintake.com/v1/usage \
  -H "Authorization: Bearer $AIMEDINTAKE_API_KEY" \
  -d from=2027-01-01T00:00:00Z \
  -d to=2027-02-01T00:00:00Z
Response · 200
{
  "data": [
    {
      "id": "usg_01JDKD0TZ7",
      "session": "ses_01JDK8Z3Q4",
      "mode": "intake",
      "completed_at": "2027-01-12T13:09:40Z",
      "units": {
        "sessions": 1
      },
      "billable": true,
      "not_billable_reason": null
    },
    {
      "id": "usg_01JDKF3N8A",
      "session": "ses_01JDKEW1C6",
      "mode": "intake",
      "completed_at": "2027-01-12T13:41:07Z",
      "units": {
        "sessions": 1
      },
      "billable": false,
      "not_billable_reason": "ended_early"
    },
    {
      "id": "usg_01JDKG8Q2D",
      "session": "ses_01JDKFZ7M9",
      "mode": "intake",
      "completed_at": "2027-01-12T13:58:22Z",
      "units": {
        "sessions": 1
      },
      "billable": false,
      "not_billable_reason": "ended_early"
    },
    {
      "id": "usg_01JDKH5T4E",
      "session": "ses_01JDKB7M2X",
      "mode": "ambient",
      "completed_at": "2027-01-12T14:21:52Z",
      "units": {
        "sessions": 1
      },
      "billable": true,
      "not_billable_reason": null
    }
  ],
  "has_more": false,
  "next_cursor": null
}
  • from and to are required. They select the half-open interval [from, to) on completed_at and may span at most 93 days.
  • Records are ordered by (completed_at, session) and paged with limit and after, as sessions are. A cursor used with a different interval returns 422 cursor_mismatch.
  • Failed and expired sessions, and sessions deleted before they completed, produce no usage record.
  • Usage records are kept after a session’s clinical data is deleted or purged, because they are the billing record.

What is billable

An intake session is billable unless one of the following holds. The rule uses the end_reason your client reported with the transcript.

Non-billable sessions
CaseWhynot_billable_reason
end_reason is initial_refusalThe patient declined before any medical question.ended_early
end_reason is emergencyThe interview was cut short to send the patient to urgent help.ended_early
end_reason is patient_stop and the transcript has fewer than 3 patient utterancesThe patient stopped before giving any clinical content.ended_early
The session belongs to a test organizationTest usage is never charged.test_organization

The three early endings share one value on purpose: the usage record tells finance that a session was not charged without revealing that it ended in an emergency. The session object carries the precise end_reason until the session is deleted. Ambient sessions have no end reason, so ended_early never applies to them: a completed ambient session is charged only in a live organization.