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
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| Parameter | Rules |
|---|---|
updated_since | Inclusive lower bound on updated_at. |
status | Return only sessions in this status. Repeat the parameter to match several. |
external_ref | Exact match on your reference: the way to find a session when you have lost its id. Cannot be combined with after. |
limit | 1 to 200. Default 50. |
after | The next_cursor of the previous page. |
{
"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
statusorupdated_sincebetween pages returns422 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:
- Store a watermark: the latest
updated_atof a run that finished without an error, kept as the exact string the API returned. - On each run, list with
updated_sinceset to the watermark minus two minutes, and page to the end. - Upsert each session by
id. For sessions that becamecompleted, fetch the result. - Save the new watermark only after the whole run has succeeded.
# 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"]const API = 'https://api.aimedintake.com/v1';
const headers = {
Authorization: `Bearer ${process.env.AIMEDINTAKE_API_KEY}`,
'Content-Type': 'application/json',
};
/** The problem code, or the HTTP status when the body is not a problem document. */
async function problemCode(response: Response): Promise<string> {
try {
return (await response.json()).code ?? `http_${response.status}`;
} catch {
return `http_${response.status}`;
}
}
import { isLater, overlapBoundary } from './timestamps'; // shown below
/**
* 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 resolves.
*/
async function sync(watermark: string): Promise<string> {
const params = new URLSearchParams({ updated_since: overlapBoundary(watermark), limit: '200' });
let newest = watermark;
for (;;) {
const response = await fetch(`${API}/sessions?${params}`, { headers });
if (!response.ok) throw new Error(`List failed: ${await problemCode(response)}`);
const page = await response.json();
for (const session of page.data) {
// Keyed by session.id; replace the stored row only if isLater(new, stored).
await upsert(session);
if (isLater(session.updated_at, newest)) newest = session.updated_at; // original string, full precision
}
if (!page.has_more) return newest;
params.set('after', page.next_cursor);
}
}# 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")// Comparing API timestamps without losing precision.
// A JavaScript Date keeps milliseconds 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.
const RFC_3339 = /^(\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2})(?:\.(\d+))?([Zz]|[+-]\d{2}:\d{2})$/;
/** Splits an RFC 3339 timestamp into its whole-second instant and its fractional digits. */
function parts(timestamp: string): [number, string] {
const match = RFC_3339.exec(timestamp);
if (!match) throw new RangeError(`Not an RFC 3339 timestamp: ${timestamp}`);
const [, whole, fraction = '', zone] = match;
// The zone belongs to the whole-second part; the fraction is the same in every zone.
// Both separators are made uppercase before parsing.
return [Date.parse(`${whole.toUpperCase()}${zone.toUpperCase()}`) / 1000, fraction.replace(/0+$/, '')];
}
/** True when `a` is a later instant than `b`, at any precision. */
export function isLater(a: string, b: string): boolean {
const [aSeconds, aFraction] = parts(a);
const [bSeconds, bFraction] = parts(b);
if (aSeconds !== bSeconds) return aSeconds > bSeconds;
return aFraction > bFraction; // digit strings without trailing zeros order like the fractions
}
/** The `updated_since` value for the next run: the watermark minus an overlap, rounded down to a second. */
export function overlapBoundary(watermark: string, overlapSeconds = 120): string {
const [seconds] = parts(watermark);
return new Date((seconds - overlapSeconds) * 1000).toISOString().replace('.000Z', 'Z');
}- 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.100Zis later than12:00:00Zbut 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 theupdated_sinceboundary 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
410from 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.
{
"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:
| deleted.reason | Meaning | What to do |
|---|---|---|
retention | The 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. |
erasure | Your 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:
| What you missed | Recoverable until |
|---|---|
| A webhook event | We retry for 72 hours. After that, a sync finds the change. |
| A result | The 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 purge | The 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
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.
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{
"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
}fromandtoare required. They select the half-open interval[from, to)oncompleted_atand may span at most 93 days.- Records are ordered by
(completed_at, session)and paged withlimitandafter, as sessions are. A cursor used with a different interval returns422 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.
| Case | Why | not_billable_reason |
|---|---|---|
end_reason is initial_refusal | The patient declined before any medical question. | ended_early |
end_reason is emergency | The 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 utterances | The patient stopped before giving any clinical content. | ended_early |
| The session belongs to a test organization | Test 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.