Skip to the content
Kusties
PhysiotherapistsTrainersClientsClinicsPricingBlog
Overview Booking API referenceReference
Log in
PhysiotherapistsTrainersClientsClinicsPricingBlog
Overview Booking API referenceReference
Log in

Kusties API · for developers

Kusties API: booking from your website

Keys, authentication, errors and limits: the overview. Every operation and field: the API reference (OpenAPI file: openapi.yaml).

Contents
  • Kopsavilkums latviski
  • 1. API or widget?
  • 2. Before you start
  • 3. What the API answers
  • 4. A specialist's website
  • 5. An organisation's website
  • 6. After the booking: read, list, cancel and reschedule
  • 7. What the patient receives
  • 8. Your website's duties
  • 9. Retries: Idempotency-Key
  • 10. When a booking is refused
  • 11. The smoke test

With the Kusties API, the server of a specialist's or an organisation's own website shows the free times in the website's own booking form, books the person who filled it in, and later reads, lists, cancels or reschedules the bookings it made. Kusties applies the same rules, limits and e-mails as on its own booking page.

This guide walks through the flows for a specialist's website and for an organisation's website, with examples in curl, Node (18 or newer, no dependencies) and PHP (8.1 or newer, with the curl extension). Every example ran unchanged against version 1 before this guide was published, and the sample answers are its real answers (the ids differ on your account). Keys, authentication, errors, limits and the conventions every part of the API shares are in the developer guide; every operation and field is in the API reference.

API version 1. This guide: 21 November 2026. Questions: info@kusties.com (quote the X-Request-ID of the request in question).

Kopsavilkums latviski#

Mājaslapas serveris ar Kusties API savā pieraksta formā rāda brīvos laikus, pieraksta klientu un vēlāk skata, atceļ vai pārceļ caur API veiktos pierakstus. Atslēgas, kļūdas un ierobežojumi ir aprakstīti izstrādātāja ceļvedī.

  • Plūsma. GET /services (pakalpojumi, uz kuriem var pierakstīties), GET /availability (brīvie laiki), tad POST /bookings. Organizācijas atslēgai pieraksts bez specialist_id tiek veikts pie jebkura tajā laikā brīva speciālista.
  • Kad tas darbojas. Pakalpojumi, brīvie laiki un jauni pieraksti darbojas tikai tad, kad pie speciālista var pierakstīties ikviens (iestatījums «Ikviens») vai organizācija ir apstiprināta. Caur API veiktos pierakstus var skatīt, atcelt un pārcelt vienmēr.
  • Mājaslapas pienākumi. Pirms pieraksta nosūtīšanas parādiet paziņojumu «Jūsu dati» ar saiti uz privacy_notice_url (no GET /me) un nosūtiet privacy_notice_shown: true. Sūtiet tikai pierakstus, ko cilvēki veic paši; darbinieki pierakstus veic pašā Kusties. Izmantojiet savu robotu pārbaudi, un pacientu datus nesaglabājiet žurnālos.
  • Atkārtoti pieprasījumi. Katram pieraksta mēģinājumam sūtiet unikālu Idempotency-Key, kurā nav pacienta datu. Ja to pašu pieprasījumu atkārtojat ar to pašu Idempotency-Key, saņemsiet to pašu pierakstu, un otrs pieraksts netiks izveidots.
  • Pārbaude. 11. nodaļas skripts testa vidē pārbauda visu ceļu: brīvos laikus, pierakstu, atkārtojumu, sarakstu, pārcelšanu un atcelšanu.

1. API or widget?#

Kusties offers two ways to take bookings on a website. Choose the API only when the website needs its own form or flow.

Booking widgetKusties API
What it istwo lines of HTML (kusties.app/embed.js) that show Kusties' booking steps in a frameyour own form; your server calls Kusties
Who builds itthe account holder pastes the code from «Pieraksts jūsu mājaslapā»your developer
LookKusties' booking steps (language, light or dark)entirely yours
The patient's datatyped into Kusties' frame: your website never sees ittyped into your form: your website sees it and sends it to Kusties
Bot protectionKusties' (Cloudflare Turnstile)yours (§8); Kusties checks the key and its limits
Your dutiesyour website's own privacy notice§8: Kusties' notice before sending, your bot check, no patient data in logs, the key's safety

Both need the account to take online bookings from anyone («Ikviens»), and both follow the same booking rules: visit types, free times, confirmation, limits and e-mails.

2. Before you start#

A key with the scopes the website uses (developer guide → Keys and scopes):

Your websiteGroups to tick in «API un integrācijas»
shows free times and books«Skatīt pakalpojumus un brīvos laikus» and «Pierakstīt» (a new key's default)
also shows a booking's status later, or lists the bookingsand «Skatīt pierakstus» (bookings:read)
also cancels or reschedulesand «Atcelt un pārcelt pierakstus» (bookings:update)

The examples below use a key with every scope.

Booking open to everyone. The catalog (GET /specialists, /locations, /services), the free times (GET /availability) and new bookings work only while the specialist takes online bookings from anyone («Kas var pierakstīties»: «Ikviens»), or while the organisation is approved. Otherwise they answer 404 booking_unavailable (an organisation's catalog: 404 organization_unavailable). Reading, listing, cancelling and rescheduling the bookings the account made through the API work in every mode; cancelling and rescheduling follow the booking's own deadline. GET /me always works.

Only bookings people make themselves. POST /bookings is for a booking a person makes through your website or app, after your form showed them Kusties' privacy notice (§8). Staff who enter a booking on someone's behalf do so in Kusties itself, not through the API.

The sandbox. Run the examples against the sandbox (https://api-sandbox.kusties.app/v1) with the kst_test_ keys Kusties sends you, and your own e-mail address and phone number (developer guide → Addresses and the sandbox). The sandbox's specialist and organisation take online bookings from anyone and allow cancelling online, so the Node and PHP flows and the smoke test cancel what they book.

3. What the API answers#

A specialist (GET /specialists, scope specialists:read): a specialist's key lists the specialist; an organisation's key, its specialists who take online bookings from anyone (only those the key is limited to).

Field
idthe specialist's id: a booking's or a free-times search's specialist_id
name, profession, photo_urlprofession and photo_url are left out when not set
time_zonethe zone of the specialist's days
cancel_hoursa patient may cancel or reschedule online until this many hours before the visit; left out: not online
max_days_aheadhow many days ahead the specialist can be booked

A location (GET /locations, scope locations:read): id, name, address, city, main and time_zone. A specialist's key lists the specialist's main address first (its id is the specialist's own id, main is true, it has no name, and address is left out while the specialist has not set it), then the practice places (a branch of an organisation is named with the organisation in address); an organisation's key lists its branches.

A service (GET /services, scope services:read): what can be booked, a specialist's visit types that anyone may book online, or an organisation's services that at least one of its specialists (whom the key reaches) offers online.

Field
ida booking's and a free-times search's service_id
name, descriptiondescription is left out when there is none
duration_minutesthe visit's length; for an organisation's service its usual length, as each specialist's own visit type sets a booking's length (the free times and the booking show the real end)
formatswhere it takes place: practice, home (the booking needs visit_address) or online; always practice for an organisation's service
price_centseuro cents: an organisation's service's price when it has one; a specialist's only where their public Kusties profile shows prices
location_idswhere it can be booked: for a visit at the practice, the main address and the practice places; for an organisation, its branches; empty for a home or online visit
specialist_idswho can be booked for it

Free times (GET /availability, scope availability:read): the free start times of one service over a range of days.

Query parameter
service_idrequired: a GET /services id
from, tothe first and last day, YYYY-MM-DD in the location's time zone, both included; left out, from is today and to is from and 6 days; at most 31 days in all
location_idonly the starts at this location (a specialist's main address: the specialist's id)
specialist_idonly this specialist's starts (an organisation's key; left out: any specialist the key reaches)
partonly the starts in a part of the day: morning (before 12:00), day (12:00–17:00) or evening (from 17:00)

The answer has from, to, time_zone and slots[], in the order of their start, location and end: each with start_time, end_time, location_id (null for a home or online visit; send it back with the booking) and specialist_ids (who is free then). When the range has no free start, next_available names the nearest one after it within the booking window (date, the day to ask for as from, and start_time); it is left out when there is none. The free times are exactly the booking page's: the working hours, the visits and blocked times, the earliest notice, the break after visits, the booking window and the daily cap.

A booking (every booking answer): it never carries the patient's name, contact details or comment.

Field
idkeep it to read, cancel or reschedule the booking later
statusbelow
start_time, end_time, time_zone
serviceid and name: what was booked, named as it was booked (a later rename, or the specialist's edit of the visit in their calendar, does not change it)
specialistid and name: whose visit it is
formatpractice, home or online; always present
locationid, name and address of the practice place, branch or main address; for a home visit only the address the patient gave; left out for an online visit
video_urlthe specialist's video link of a confirmed online visit; never for a request, or a cancelled visit
cancel_untilthe online cancelling and rescheduling deadline, only while the booking is requested or scheduled (also once it has passed; can_cancel is then false); left out when the specialist does not allow cancelling online
can_cancel, can_reschedulewhether the booking can be cancelled or rescheduled online now
created_atwhen it was booked
statusMeaning
requestedwaits for the specialist (or the organisation's reception) to confirm; the time is held
scheduledbooked (also after the patient confirmed they will come)
declinedthe specialist declined the request, or nobody answered it before the visit came too close (the time is free again)
cancelledcancelled: by the patient through their e-mailed link, by the specialist (also a visit they deleted from their calendar), or by you
pastthe visit's time is over, whether it took place or not

4. A specialist's website#

  1. GET /me: the account's name and privacy_notice_url, the notice your form links (§8), and the key's scopes.
  2. GET /services: the visit types anyone may book online, each with its formats (home needs the patient's address) and price. GET /locations names the places, and GET /specialists gives cancel_hours and max_days_ahead.
  3. GET /availability?service_id=…: the free starts of a visit type for a week from today, or for the days you ask (from, to), at one place (location_id) or in a part of the day (part). Show them in time_zone. When the range has none, offer next_available.
  4. Your form asks for the fields below, shows Kusties' notice (§8) and, for a home visit, the address.
  5. POST /bookings with an Idempotency-Key (§9). The answer is 201 with the booking: scheduled when the specialist confirms new clients automatically, otherwise requested (the specialist confirms or declines it). Say so as Kusties' own page does: «Pieraksts apstiprināts. Apstiprinājums ir nosūtīts uz jūsu e-pastu.» ("Booking confirmed. The confirmation has been sent to your e-mail.") or «Pieprasījums nosūtīts. Speciālists to vēl apstiprinās. Jūs saņemsiet e-pastu, tiklīdz tas būs izdarīts.» ("Request sent. The specialist still has to confirm it. You will get an e-mail as soon as they do."). Keep booking.id if your website will show, cancel or reschedule the booking later.
FieldRequiredRules
service_idyesa GET /services id
start_timeyesa slot's start_time, as received (any offset is accepted)
location_idrecommendedthe slot's location_id (the specialist's id for the main address; null for a home or online visit). If that start is now at another place, the booking is refused like a taken time (409 booking_slot_taken); left out or null, it is not checked
specialist_idnoan organisation's key: one of the slot's specialist_ids (left out: any specialist free then, §5); a specialist's key: leave it out
client.first_name, client.last_nameyesat most 100 characters each
client.emailyesan e-mail address, at most 255 characters
client.phoneyesa Latvian number (8 digits, starting with 2 or 6) or + (or 00) and the country code; spaces, dashes, dots, slashes and brackets are ignored; at most 30 characters
client.languagenolv (default) or en: the language of the patient's e-mails
commentnoat most 300 characters, read only by the specialist; show the hint in §8
visit_addressfor a home visitwhere the visit takes place (a service with formats: ["home"]), at most 200 characters; ignored for other visits
privacy_notice_shownyes, trueyour form showed Kusties' notice before sending (§8); false or missing: 400

The same booking rules apply as on Kusties' own page: the time must still be free when the request arrives (otherwise 409 booking_slot_taken: show the free times again), and the page's limits apply (developer guide → Limits). Whether the person is already the specialist's client never changes the answer.

curl. First the address and the key, in the shell's environment:

# The sandbox (live: https://api.kusties.app/v1) and your key from «API un integrācijas»; keep the key
      # out of every file you commit
      export BASE=https://api-sandbox.kusties.app/v1
      export KUSTIES_API_KEY=kst_test_…
      

Then the key's account and its catalog:

# The key and the account it acts for (privacy_notice_url: the notice your form links)
      curl -sS "$BASE/me" -H "Authorization: Bearer $KUSTIES_API_KEY"

      # The specialist (cancel_hours: the online cancelling deadline), the places and what can be booked
      curl -sS "$BASE/specialists" -H "Authorization: Bearer $KUSTIES_API_KEY"
      curl -sS "$BASE/locations" -H "Authorization: Bearer $KUSTIES_API_KEY"
      curl -sS "$BASE/services" -H "Authorization: Bearer $KUSTIES_API_KEY"
      

The answers of /me, /services and /locations:

{
        "key": {
          "id": "e5ba05c6-959b-43cd-9c96-4b1836ac6cfc",
          "name": "Annas mājaslapa",
          "scopes": [
            "specialists:read",
            "locations:read",
            "services:read",
            "availability:read",
            "bookings:read",
            "bookings:create",
            "bookings:update"
          ],
          "expires_at": null,
          "ip_restricted": false,
          "sandbox": true,
          "specialist_ids": []
        },
        "account": {
          "type": "specialist",
          "id": "f147239b-c511-4afd-941e-1e9ebbbda477",
          "name": "Anna Bērziņa",
          "time_zone": "Europe/Riga",
          "privacy_notice_url": "https://kusties.com/pacientiem"
        }
      }
      
{
        "data": [
          {
            "id": "dab8e38f-c573-422f-ac8c-63cf078aa717",
            "name": "Konsultācija",
            "duration_minutes": 60,
            "formats": [
              "practice"
            ],
            "price_cents": 4500,
            "location_ids": [
              "f147239b-c511-4afd-941e-1e9ebbbda477",
              "74e11dfd-094e-40a0-8ed5-34f4cf8a4583"
            ],
            "specialist_ids": [
              "f147239b-c511-4afd-941e-1e9ebbbda477"
            ]
          },
          {
            "id": "757f47c2-6136-4cd0-a9a6-29a060c10923",
            "name": "Mājas vizīte",
            "duration_minutes": 90,
            "formats": [
              "home"
            ],
            "location_ids": [],
            "specialist_ids": [
              "f147239b-c511-4afd-941e-1e9ebbbda477"
            ]
          }
        ],
        "next_cursor": null
      }
      
{
        "data": [
          {
            "id": "f147239b-c511-4afd-941e-1e9ebbbda477",
            "address": "Tērbatas iela 14, Rīga",
            "main": true,
            "time_zone": "Europe/Riga"
          },
          {
            "id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "name": "Rīga",
            "address": "Kustību centrs, Brīvības iela 1",
            "main": false,
            "time_zone": "Europe/Riga"
          }
        ],
        "next_cursor": null
      }
      

Then a day's free times of a service, with its id in SERVICE_ID:

# The service's free times on one day (from and to are days in time_zone; left out: a week from today)
      curl -sS "$BASE/availability?service_id=$SERVICE_ID&from=2026-11-24&to=2026-11-24" \
        -H "Authorization: Bearer $KUSTIES_API_KEY"
      
{
        "from": "2026-11-24",
        "to": "2026-11-24",
        "time_zone": "Europe/Riga",
        "slots": [
          {
            "start_time": "2026-11-24T07:00:00Z",
            "end_time": "2026-11-24T08:00:00Z",
            "location_id": "f147239b-c511-4afd-941e-1e9ebbbda477",
            "specialist_ids": [
              "f147239b-c511-4afd-941e-1e9ebbbda477"
            ]
          },
          {
            "start_time": "2026-11-24T08:00:00Z",
            "end_time": "2026-11-24T09:00:00Z",
            "location_id": "f147239b-c511-4afd-941e-1e9ebbbda477",
            "specialist_ids": [
              "f147239b-c511-4afd-941e-1e9ebbbda477"
            ]
          },
          {
            "start_time": "2026-11-24T12:00:00Z",
            "end_time": "2026-11-24T13:00:00Z",
            "location_id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "specialist_ids": [
              "f147239b-c511-4afd-941e-1e9ebbbda477"
            ]
          },
          {
            "start_time": "2026-11-24T13:00:00Z",
            "end_time": "2026-11-24T14:00:00Z",
            "location_id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "specialist_ids": [
              "f147239b-c511-4afd-941e-1e9ebbbda477"
            ]
          }
        ]
      }
      

Book one of them, with its start_time and location_id in START and LOCATION_ID:

# Book a free start (a new Idempotency-Key for every booking attempt)
      curl -sS -X POST "$BASE/bookings" \
        -H "Authorization: Bearer $KUSTIES_API_KEY" \
        -H "Content-Type: application/json" \
        -H "Idempotency-Key: 9f1c6c52-3a4e-4d8e-9a57-2b0e6f6d1c11" \
        -d @- <<JSON
      {
        "service_id": "$SERVICE_ID",
        "start_time": "$START",
        "location_id": "$LOCATION_ID",
        "client": {"first_name": "Anna", "last_name": "Bērziņa", "email": "anna@example.com", "phone": "+371 2000 0000", "language": "lv"},
        "comment": "",
        "privacy_notice_shown": true
      }
      JSON
      

The booking (201):

{
        "id": "0d009a40-837b-4c24-8e6f-fac790897f6f",
        "status": "scheduled",
        "start_time": "2026-11-24T07:00:00Z",
        "end_time": "2026-11-24T08:00:00Z",
        "time_zone": "Europe/Riga",
        "service": {
          "id": "dab8e38f-c573-422f-ac8c-63cf078aa717",
          "name": "Konsultācija"
        },
        "specialist": {
          "id": "f147239b-c511-4afd-941e-1e9ebbbda477",
          "name": "Anna Bērziņa"
        },
        "format": "practice",
        "location": {
          "id": "f147239b-c511-4afd-941e-1e9ebbbda477",
          "address": "Tērbatas iela 14, Rīga"
        },
        "cancel_until": "2026-11-23T07:00:00Z",
        "can_cancel": true,
        "can_reschedule": true,
        "created_at": "2026-11-21T21:13:24.274764Z"
      }
      

A home visit has no location_id: the patient's address goes in visit_address, and the booking's location is that address. With the home visit's id in HOME_SERVICE_ID and a free start of it in HOME_START:

# A home visit: no location_id, the patient's address in visit_address instead
      curl -sS -X POST "$BASE/bookings" \
        -H "Authorization: Bearer $KUSTIES_API_KEY" \
        -H "Content-Type: application/json" \
        -H "Idempotency-Key: 3b2f8d0e-5c1a-4f7e-9d6b-8a4c2e1f0b93" \
        -d @- <<JSON
      {
        "service_id": "$HOME_SERVICE_ID",
        "start_time": "$HOME_START",
        "client": {"first_name": "Jānis", "last_name": "Ozols", "email": "janis@example.com", "phone": "29000000"},
        "visit_address": "Ozolu iela 7-12, Rīga",
        "privacy_notice_shown": true
      }
      JSON
      
{
        "id": "97d3564d-7029-40ef-b91b-1cf1cd3a3e59",
        "status": "scheduled",
        "start_time": "2026-11-26T07:00:00Z",
        "end_time": "2026-11-26T08:30:00Z",
        "time_zone": "Europe/Riga",
        "service": {
          "id": "757f47c2-6136-4cd0-a9a6-29a060c10923",
          "name": "Mājas vizīte"
        },
        "specialist": {
          "id": "f147239b-c511-4afd-941e-1e9ebbbda477",
          "name": "Anna Bērziņa"
        },
        "format": "home",
        "location": {
          "address": "Ozolu iela 7-12, Rīga"
        },
        "cancel_until": "2026-11-25T07:00:00Z",
        "can_cancel": true,
        "can_reschedule": true,
        "created_at": "2026-11-21T21:13:24.336192Z"
      }
      

Node. The flows below are tests for the sandbox: each books a time past the online cancelling deadline and cancels the booking at the end, so a run leaves nothing behind; your own form lets the patient choose from all the free times. A small client, kusties.mjs, used by both flows:

// kusties.mjs: a small client for the Kusties API (Node 18 or newer, no dependencies).
      // Run it on your server only: the key comes from the server's environment, never from the browser.
      import { randomUUID } from 'node:crypto';

      const BASE = process.env.KUSTIES_API_BASE ?? 'https://api-sandbox.kusties.app/v1';
      const KEY = process.env.KUSTIES_API_KEY;
      if (!KEY) throw new Error('KUSTIES_API_KEY is not set');

      // An error answer of the API. Act on code (and on fields for validation_failed).
      export class KustiesError extends Error {
        constructor(status, body, headers) {
          super(body?.message ?? `Kusties answered ${status}`);
          this.name = 'KustiesError';
          this.status = status;
          this.code = body?.code ?? null; // e.g. 'booking_slot_taken'; null when the answer was not Kusties' JSON
          this.fields = body?.fields ?? []; // [{ field, code, message }] for validation_failed
          this.metadata = body?.metadata ?? {};
          this.retryAfter = Number(headers.get('retry-after')) || null; // seconds, on a 429
          this.requestId = headers.get('x-request-id'); // quote it when you contact Kusties
        }
      }

      // One request: query holds the query parameters, body the JSON body.
      export async function kusties(path, { method = 'GET', query = {}, body, idempotencyKey } = {}) {
        const url = new URL(BASE + path);
        for (const [name, value] of Object.entries(query)) {
          if (value !== undefined && value !== null && value !== '') url.searchParams.set(name, String(value));
        }

        const headers = { Authorization: `Bearer ${KEY}`, Accept: 'application/json' };
        if (body !== undefined) headers['Content-Type'] = 'application/json';
        if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;

        const res = await fetch(url, {
          method,
          headers,
          body: body === undefined ? undefined : JSON.stringify(body),
          redirect: 'error', // never follow a redirect with the key
          signal: AbortSignal.timeout(15_000),
        });

        const text = await res.text();
        let data = null;
        try {
          data = text ? JSON.parse(text) : null;
        } catch {
          // not JSON: a proxy's error page
        }

        if (!res.ok) throw new KustiesError(res.status, data, res.headers);

        return { data, replayed: res.headers.get('idempotent-replayed') === 'true', requestId: res.headers.get('x-request-id') };
      }

      // Sends a booking with one Idempotency-Key for every attempt, so a retry after a timeout, a lost
      // connection or a 5xx answer never books twice. Other refusals are not retried.
      export async function book(body, attempts = 3) {
        const idempotencyKey = randomUUID();

        for (let attempt = 1; ; attempt++) {
          try {
            return await kusties('/bookings', { method: 'POST', body, idempotencyKey });
          } catch (err) {
            const transient = !(err instanceof KustiesError) || err.status >= 500;
            if (!transient || attempt >= attempts) throw err;
            await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
          }
        }
      }

      // A day (YYYY-MM-DD) in a time zone, as the API's from and to take it.
      export function dayIn(timeZone, date = new Date()) {
        return new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(date);
      }

      // The day after a day (YYYY-MM-DD).
      function nextDay(day) {
        return new Date(Date.parse(`${day}T00:00:00Z`) + 86_400_000).toISOString().slice(0, 10);
      }

      // The first free start at or after notBefore (a Date) of an availability answer (path: /availability,
      // or a booking's /bookings/{id}/availability), a week at a time from notBefore's day: the next week
      // when this week's free starts are all earlier, next_available's day when the week has none.
      // null: nothing free within the booking window.
      export async function firstFreeStart(path, query, notBefore = new Date(), timeZone = 'Europe/Riga') {
        let from = dayIn(timeZone, notBefore);

        for (let weeks = 0; weeks < 26; weeks++) {
          const { data: week } = await kusties(path, { query: { ...query, from } });
          const slot = week.slots.find((s) => new Date(s.start_time) >= notBefore);
          if (slot) return slot;

          if (week.slots.length) from = nextDay(week.to);
          else if (week.next_available) from = week.next_available.date;
          else return null;
        }

        return null;
      }
      

specialist-flow.mjs:

// specialist-flow.mjs: a specialist's key with every scope, on the sandbox:
      //   KUSTIES_API_KEY=kst_test_… TEST_EMAIL=you@example.com TEST_PHONE=+37120000000 node specialist-flow.mjs
      import { book, firstFreeStart, kusties, KustiesError } from './kusties.mjs';

      // 1. The account (and the notice your form links), the specialist (the cancel deadline) and what can be booked
      const { data: me } = await kusties('/me');
      const { data: specialists } = await kusties('/specialists');
      const { data: services } = await kusties('/services');
      const specialist = specialists.data[0];
      const service = services.data.find((s) => s.formats.includes('practice')); // a home visit also needs visit_address
      console.log(me.account.name, '·', service.name, `${service.duration_minutes} min`, '· notice:', me.account.privacy_notice_url);

      // 2. A free time past the online cancelling deadline (cancel_hours; left out: no cancelling online), so this
      //    test can cancel the booking it makes. Your form shows the patient every free time of the week instead.
      const notBefore = new Date(Date.now() + ((specialist.cancel_hours ?? 0) + 1) * 3_600_000);
      const slot = await firstFreeStart('/availability', { service_id: service.id }, notBefore, specialist.time_zone);
      if (!slot) throw new Error('No free time within the booking window');

      // 3. The booking, after the patient filled in your form and saw the «Jūsu dati» notice
      const client = { first_name: 'Anna', last_name: 'Bērziņa', email: process.env.TEST_EMAIL, phone: process.env.TEST_PHONE, language: 'lv' };
      if (!client.email || !client.phone) throw new Error('Set TEST_EMAIL and TEST_PHONE to your own address and number');

      try {
        const { data: booking, replayed } = await book({
          service_id: service.id,
          start_time: slot.start_time, // exactly as the availability gave it
          location_id: slot.location_id, // the place you showed (the specialist's id is their main address)
          client, // language: the language of the patient's e-mails
          comment: '',
          privacy_notice_shown: true, // only when your form showed the notice
        });
        console.log('booked', booking.id, booking.status, booking.start_time, replayed ? '(replayed)' : '');

        // 4. Later: the booking's status (bookings:read), then cancel it while the specialist allows that online
        const { data: now } = await kusties(`/bookings/${booking.id}`);
        console.log('status', now.status, '· can cancel:', now.can_cancel, '· until', now.cancel_until ?? '-');

        if (now.can_cancel) {
          const { data: cancelled } = await kusties(`/bookings/${booking.id}/cancel`, { method: 'POST' });
          console.log('status', cancelled.status);
        }
      } catch (err) {
        if (!(err instanceof KustiesError)) throw err;

        // Tell the patient what to do; log only the code and the request id, never the form
        switch (err.code) {
          case 'booking_slot_taken':
            console.log('That time was just taken: show the free times again.');
            break;
          case 'validation_failed':
            console.log('Check these fields:', err.fields.map((f) => `${f.field} (${f.code})`).join(', '));
            break;
          case 'booking_limit_reached':
          case 'api_daily_limit_reached':
          case 'rate_limited':
            console.log('Online booking is not possible right now; please call the practice.', err.retryAfter ?? '');
            break;
          default:
            console.log('Kusties refused:', err.status, err.code, 'request', err.requestId);
        }
      }
      

PHP. The client, kusties.php:

<?php
      // kusties.php: a small client for the Kusties API (PHP 8.1 or newer, with curl and json).
      // Run it on your server only: the key comes from the server's environment, never from the browser.

      declare(strict_types=1);

      // An error answer of the API. Act on $errorCode (and on $fields for validation_failed).
      final class KustiesError extends RuntimeException
      {
          public function __construct(
              public readonly int $status,
              public readonly ?string $errorCode,   // e.g. 'booking_slot_taken'; null when the answer was not Kusties' JSON
              public readonly array $fields,        // [['field' => …, 'code' => …, 'message' => …]] for validation_failed
              public readonly array $metadata,
              public readonly ?int $retryAfter,     // seconds, on a 429
              public readonly ?string $requestId,   // quote it when you contact Kusties
              string $message,
          ) {
              parent::__construct($message, $status);
          }
      }

      // One request: $query holds the query parameters, $body the JSON body.
      function kusties(string $method, string $path, array $query = [], ?array $body = null, ?string $idempotencyKey = null): array
      {
          $base = getenv('KUSTIES_API_BASE') ?: 'https://api-sandbox.kusties.app/v1';
          $key = getenv('KUSTIES_API_KEY');
          if (!$key) {
              throw new LogicException('KUSTIES_API_KEY is not set');
          }

          $query = array_filter($query, fn ($value) => $value !== null && $value !== '');
          $url = $base . $path . ($query ? '?' . http_build_query($query) : '');

          $headers = ['Authorization: Bearer ' . $key, 'Accept: application/json'];
          if ($body !== null) {
              $headers[] = 'Content-Type: application/json';
          }
          if ($idempotencyKey !== null) {
              $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
          }

          $responseHeaders = [];
          $ch = curl_init($url);
          curl_setopt_array($ch, [
              CURLOPT_CUSTOMREQUEST => $method,
              CURLOPT_HTTPHEADER => $headers,
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_PROTOCOLS => CURLPROTO_HTTPS, // TLS only
              CURLOPT_FOLLOWLOCATION => false,      // never follow a redirect with the key
              CURLOPT_CONNECTTIMEOUT => 5,
              CURLOPT_TIMEOUT => 15,
              CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$responseHeaders): int {
                  $parts = explode(':', $line, 2);
                  if (count($parts) === 2) {
                      $responseHeaders[strtolower(trim($parts[0]))] = trim($parts[1]);
                  }

                  return strlen($line);
              },
          ]);
          if ($body !== null) {
              curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
          }

          $raw = curl_exec($ch);
          if ($raw === false) {
              throw new RuntimeException('Kusties could not be reached: ' . curl_error($ch));
          }
          $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

          $data = $raw === '' ? null : json_decode($raw, true);
          if ($status >= 400) {
              throw new KustiesError(
                  $status,
                  $data['code'] ?? null,
                  $data['fields'] ?? [],
                  $data['metadata'] ?? [],
                  isset($responseHeaders['retry-after']) ? (int) $responseHeaders['retry-after'] : null,
                  $responseHeaders['x-request-id'] ?? null,
                  $data['message'] ?? 'Kusties answered ' . $status,
              );
          }

          return [
              'data' => $data,
              'replayed' => ($responseHeaders['idempotent-replayed'] ?? '') === 'true',
              'request_id' => $responseHeaders['x-request-id'] ?? null,
          ];
      }

      // Sends a booking with one Idempotency-Key for every attempt, so a retry after a timeout, a lost
      // connection or a 5xx answer never books twice. Other refusals are not retried.
      function kusties_book(array $body, int $attempts = 3): array
      {
          $idempotencyKey = bin2hex(random_bytes(16));

          for ($attempt = 1; ; $attempt++) {
              try {
                  return kusties('POST', '/bookings', [], $body, $idempotencyKey);
              } catch (KustiesError $e) {
                  if ($e->status < 500 || $attempt >= $attempts) {
                      throw $e;
                  }
              } catch (RuntimeException $e) {
                  if ($attempt >= $attempts) {
                      throw $e;
                  }
              }
              sleep($attempt);
          }
      }

      // The first free start at or after $notBefore of an availability answer ($path: /availability, or a booking's
      // /bookings/{id}/availability), a week at a time from $notBefore's day: the next week when this week's free starts
      // are all earlier, next_available's day when the week has none. null: nothing free within the booking window.
      function kusties_first_free_start(string $path, array $query, DateTimeImmutable $notBefore, string $timeZone = 'Europe/Riga'): ?array
      {
          $from = $notBefore->setTimezone(new DateTimeZone($timeZone))->format('Y-m-d');

          for ($weeks = 0; $weeks < 26; $weeks++) {
              $week = kusties('GET', $path, ['from' => $from] + $query)['data'];
              foreach ($week['slots'] as $slot) {
                  if (new DateTimeImmutable($slot['start_time']) >= $notBefore) {
                      return $slot;
                  }
              }

              if ($week['slots'] !== []) {
                  $from = (new DateTimeImmutable($week['to']))->modify('+1 day')->format('Y-m-d');
              } elseif (isset($week['next_available'])) {
                  $from = $week['next_available']['date'];
              } else {
                  return null;
              }
          }

          return null;
      }
      

specialist-flow.php:

<?php
      // specialist-flow.php: a specialist's key with every scope, on the sandbox:
      //   KUSTIES_API_KEY=kst_test_… TEST_EMAIL=you@example.com TEST_PHONE=+37120000000 php specialist-flow.php

      declare(strict_types=1);

      require __DIR__ . '/kusties.php';

      // 1. The account (and the notice your form links), the specialist (the cancel deadline) and what can be booked
      $me = kusties('GET', '/me')['data'];
      $specialist = kusties('GET', '/specialists')['data']['data'][0];
      $service = null;
      foreach (kusties('GET', '/services')['data']['data'] as $candidate) {
          if (in_array('practice', $candidate['formats'], true)) { // a home visit also needs visit_address
              $service = $candidate;
              break;
          }
      }
      echo $me['account']['name'], ' · ', $service['name'], ' · notice: ', $me['account']['privacy_notice_url'], "\n";

      // 2. A free time past the online cancelling deadline (cancel_hours; left out: no cancelling online), so this
      //    test can cancel the booking it makes. Your form shows the patient every free time of the week instead.
      $notBefore = new DateTimeImmutable(sprintf('+%d hours', ($specialist['cancel_hours'] ?? 0) + 1));
      $slot = kusties_first_free_start('/availability', ['service_id' => $service['id']], $notBefore, $specialist['time_zone']);
      if ($slot === null) {
          throw new RuntimeException('No free time within the booking window');
      }

      // 3. The booking, after the patient filled in your form and saw the «Jūsu dati» notice
      $client = ['first_name' => 'Anna', 'last_name' => 'Bērziņa', 'email' => getenv('TEST_EMAIL'), 'phone' => getenv('TEST_PHONE'), 'language' => 'lv'];
      if (!$client['email'] || !$client['phone']) {
          throw new LogicException('Set TEST_EMAIL and TEST_PHONE to your own address and number');
      }

      try {
          $answer = kusties_book([
              'service_id' => $service['id'],
              'start_time' => $slot['start_time'],   // exactly as the availability gave it
              'location_id' => $slot['location_id'], // the place you showed (the specialist's id is their main address)
              'client' => $client,                   // language: the language of the patient's e-mails
              'comment' => '',
              'privacy_notice_shown' => true,        // only when your form showed the notice
          ]);
          $booking = $answer['data'];
          echo 'booked ', $booking['id'], ' ', $booking['status'], ' ', $booking['start_time'], $answer['replayed'] ? ' (replayed)' : '', "\n";

          // 4. Later: the booking's status (bookings:read), then cancel it while the specialist allows that online
          $now = kusties('GET', '/bookings/' . $booking['id'])['data'];
          echo 'status ', $now['status'], ' · can cancel: ', $now['can_cancel'] ? 'yes' : 'no', ' · until ', $now['cancel_until'] ?? '-', "\n";

          if ($now['can_cancel']) {
              $cancelled = kusties('POST', '/bookings/' . $booking['id'] . '/cancel')['data'];
              echo 'status ', $cancelled['status'], "\n";
          }
      } catch (KustiesError $e) {
          // Tell the patient what to do; log only the code and the request id, never the form
          echo match ($e->errorCode) {
              'booking_slot_taken' => 'That time was just taken: show the free times again.',
              'validation_failed' => 'Check these fields: ' . implode(', ', array_map(fn ($f) => $f['field'] . ' (' . $f['code'] . ')', $e->fields)),
              'booking_limit_reached', 'api_daily_limit_reached', 'rate_limited' => 'Online booking is not possible right now; please call the practice.',
              default => 'Kusties refused: ' . $e->status . ' ' . $e->errorCode . ' request ' . $e->requestId,
          }, "\n";
      }
      

5. An organisation's website#

  1. GET /me, GET /specialists (the organisation's specialists who take online bookings from anyone), GET /locations (its branches) and GET /services (each with the branches in location_ids and the specialists who offer it in specialist_ids). An organisation's catalog answers 404 organization_unavailable while the organisation is not approved or is suspended.
  2. GET /availability?service_id=…&location_id=…, optionally narrowed by specialist_id (one of the service's specialist_ids) and part. Each slot names the specialists free then in specialist_ids. Each specialist offers the service with a visit type of their own, which sets its length, so one start can come as two slots with different ends (in the answer below, 12:00 UTC once for 45 minutes and once for 60).
  3. POST /bookings with the slot's location_id (its branch) and, optionally, specialist_id (one of the slot's specialist_ids). Without it, Kusties books any specialist free at that time: the one with the fewest visits that week (ties at random). The booking is that specialist's, and specialist says who; when the organisation's reception answers that specialist's requests, the reception confirms the request. 409 booking_slot_taken when nobody (or not the chosen specialist) is free then, or the start is no longer at that branch; a specialist who does not offer the service has no free times, and a booking that names them is refused the same way. An organisation's services always take place at a branch, so visit_address is not used.

A key limited to some specialists (developer guide → Keys and scopes) reaches only them: GET /specialists, /services and the free times show only them, a booking without specialist_id picks only among them, the other specialists' bookings answer 404 booking_not_found and are left out of GET /bookings, and a request that names another specialist is refused:

{
        "success": false,
        "error": "forbidden",
        "message": "This API key does not reach this specialist",
        "code": "api_key_specialist_not_allowed",
        "timestamp": "2026-11-21T21:13:24.654586Z",
        "request_id": "eee86cad-d0d0-4a86-988c-dc840b878b29",
        "path": "/v1/availability",
        "method": "GET",
        "metadata": {
          "specialist_id": "f147239b-c511-4afd-941e-1e9ebbbda477"
        }
      }
      

curl, with the organisation's key in KUSTIES_API_KEY:

# The organisation's team, branches and services (with the organisation's key in KUSTIES_API_KEY)
      curl -sS "$BASE/specialists" -H "Authorization: Bearer $KUSTIES_API_KEY"
      curl -sS "$BASE/locations" -H "Authorization: Bearer $KUSTIES_API_KEY"
      curl -sS "$BASE/services" -H "Authorization: Bearer $KUSTIES_API_KEY"
      

The services answer:

{
        "data": [
          {
            "id": "ca9b70dc-ab86-444f-ba37-4c3fb8804a51",
            "name": "Muguras konsultācija",
            "description": "Pirmā vizīte",
            "duration_minutes": 60,
            "formats": [
              "practice"
            ],
            "price_cents": 5000,
            "location_ids": [
              "74e11dfd-094e-40a0-8ed5-34f4cf8a4583"
            ],
            "specialist_ids": [
              "934f24a7-f0a5-44d3-a674-17d6df612682",
              "f147239b-c511-4afd-941e-1e9ebbbda477"
            ]
          }
        ],
        "next_cursor": null
      }
      

A day's free times of the service at a branch, with the service's id in SERVICE_ID and the branch's in LOCATION_ID:

# A service's free times at a branch in the day part (12:00–17:00) of one day, with any specialist
      # (add specialist_id for one)
      curl -sS "$BASE/availability?service_id=$SERVICE_ID&location_id=$LOCATION_ID&from=2026-11-24&to=2026-11-24&part=day" \
        -H "Authorization: Bearer $KUSTIES_API_KEY"
      
{
        "from": "2026-11-24",
        "to": "2026-11-24",
        "time_zone": "Europe/Riga",
        "slots": [
          {
            "start_time": "2026-11-24T10:00:00Z",
            "end_time": "2026-11-24T10:45:00Z",
            "location_id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "specialist_ids": [
              "934f24a7-f0a5-44d3-a674-17d6df612682"
            ]
          },
          {
            "start_time": "2026-11-24T11:00:00Z",
            "end_time": "2026-11-24T11:45:00Z",
            "location_id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "specialist_ids": [
              "934f24a7-f0a5-44d3-a674-17d6df612682"
            ]
          },
          {
            "start_time": "2026-11-24T12:00:00Z",
            "end_time": "2026-11-24T12:45:00Z",
            "location_id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "specialist_ids": [
              "934f24a7-f0a5-44d3-a674-17d6df612682"
            ]
          },
          {
            "start_time": "2026-11-24T12:00:00Z",
            "end_time": "2026-11-24T13:00:00Z",
            "location_id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "specialist_ids": [
              "f147239b-c511-4afd-941e-1e9ebbbda477"
            ]
          },
          {
            "start_time": "2026-11-24T13:00:00Z",
            "end_time": "2026-11-24T13:45:00Z",
            "location_id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "specialist_ids": [
              "934f24a7-f0a5-44d3-a674-17d6df612682"
            ]
          },
          {
            "start_time": "2026-11-24T13:00:00Z",
            "end_time": "2026-11-24T14:00:00Z",
            "location_id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "specialist_ids": [
              "f147239b-c511-4afd-941e-1e9ebbbda477"
            ]
          },
          {
            "start_time": "2026-11-24T14:00:00Z",
            "end_time": "2026-11-24T14:45:00Z",
            "location_id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
            "specialist_ids": [
              "934f24a7-f0a5-44d3-a674-17d6df612682"
            ]
          }
        ]
      }
      

Book the first start, in START:

# Book it with any specialist free then (for one, add "specialist_id": one of the slot's specialist_ids)
      curl -sS -X POST "$BASE/bookings" \
        -H "Authorization: Bearer $KUSTIES_API_KEY" \
        -H "Content-Type: application/json" \
        -H "Idempotency-Key: 4d0a8e1f-77b2-4c0e-a1d3-5e9f0b2c6a40" \
        -d @- <<JSON
      {
        "service_id": "$SERVICE_ID",
        "start_time": "$START",
        "location_id": "$LOCATION_ID",
        "client": {"first_name": "Anna", "last_name": "Bērziņa", "email": "anna@example.com", "phone": "+371 2000 0000", "language": "en"},
        "privacy_notice_shown": true
      }
      JSON
      
{
        "id": "96c6b64e-b341-43e4-9875-ed41f11ae0e1",
        "status": "scheduled",
        "start_time": "2026-11-24T10:00:00Z",
        "end_time": "2026-11-24T10:45:00Z",
        "time_zone": "Europe/Riga",
        "service": {
          "id": "ca9b70dc-ab86-444f-ba37-4c3fb8804a51",
          "name": "Muguras konsultācija"
        },
        "specialist": {
          "id": "934f24a7-f0a5-44d3-a674-17d6df612682",
          "name": "Jānis Kalns"
        },
        "format": "practice",
        "location": {
          "id": "74e11dfd-094e-40a0-8ed5-34f4cf8a4583",
          "name": "Rīga",
          "address": "Kustību centrs, Brīvības iela 1"
        },
        "cancel_until": "2026-11-23T10:00:00Z",
        "can_cancel": true,
        "can_reschedule": true,
        "created_at": "2026-11-21T21:13:24.590958Z"
      }
      

Node, organization-flow.mjs (with kusties.mjs from §4):

// organization-flow.mjs: an organisation's key with every scope, on the sandbox:
      //   KUSTIES_API_KEY=kst_test_… TEST_EMAIL=you@example.com TEST_PHONE=+37120000000 node organization-flow.mjs
      import { book, firstFreeStart, kusties, KustiesError } from './kusties.mjs';

      // 1. The organisation, its team, its branches and the services it offers online
      const { data: me } = await kusties('/me');
      const { data: specialists } = await kusties('/specialists');
      const { data: locations } = await kusties('/locations');
      const { data: services } = await kusties('/services');
      const service = services.data[0];
      const branch = locations.data.find((l) => service.location_ids.includes(l.id));
      console.log(me.account.name, '·', service.name, '·', branch.name, '· notice:', me.account.privacy_notice_url);

      // 2. A free time of the service at the branch, with any specialist (add specialist_id: one of service.specialist_ids
      //    for one, part: 'morning' | 'day' | 'evening' for a part of the day). Past the latest online cancelling
      //    deadline of the service's specialists, so this test can cancel what it books. Your form shows the patient
      //    every free time of the week instead.
      const team = specialists.data.filter((s) => service.specialist_ids.includes(s.id));
      const hours = Math.max(0, ...team.map((s) => s.cancel_hours ?? 0));
      const notBefore = new Date(Date.now() + (hours + 1) * 3_600_000);
      const slot = await firstFreeStart('/availability', { service_id: service.id, location_id: branch.id }, notBefore, branch.time_zone);
      if (!slot) throw new Error('No free time within the booking window');
      console.log('free at', slot.start_time, `(${slot.specialist_ids.length} free)`);

      // 3. The booking: no specialist_id means any specialist free then (the least busy that week)
      const client = { first_name: 'Anna', last_name: 'Bērziņa', email: process.env.TEST_EMAIL, phone: process.env.TEST_PHONE, language: 'en' };
      if (!client.email || !client.phone) throw new Error('Set TEST_EMAIL and TEST_PHONE to your own address and number');

      try {
        const { data: booking } = await book({
          service_id: service.id,
          start_time: slot.start_time,
          location_id: slot.location_id, // the branch you showed
          client,
          privacy_notice_shown: true,
        });
        console.log('booked', booking.id, booking.status, 'with', booking.specialist.name, 'until', booking.end_time);

        // 4. Reschedule it to a later free time of the same specialist, while the specialist allows that online
        if (booking.can_reschedule) {
          const after = new Date(Date.parse(booking.start_time) + 60_000); // not its own start
          const other = await firstFreeStart(`/bookings/${booking.id}/availability`, {}, after, booking.time_zone);

          if (other) {
            const { data: moved } = await kusties(`/bookings/${booking.id}/reschedule`, { method: 'POST', body: { start_time: other.start_time } });
            console.log('rescheduled to', moved.start_time);
          }
        }

        // 5. The account's open bookings, page by page (the patient can also cancel or reschedule through
        //    Kusties' e-mail, so read them again before you show them)
        let cursor;
        do {
          const { data: page } = await kusties('/bookings', { query: { status: 'requested,scheduled', limit: 50, cursor } });
          for (const b of page.data) console.log('open', b.id, b.status, b.start_time, b.specialist.name);
          cursor = page.next_cursor;
        } while (cursor);

        // 6. Cancel it while the specialist allows that online
        const { data: now } = await kusties(`/bookings/${booking.id}`);

        if (now.can_cancel) {
          const { data: cancelled } = await kusties(`/bookings/${booking.id}/cancel`, { method: 'POST' });
          console.log('status', cancelled.status);
        } else {
          // Past cancel_until, or the specialist does not allow cancelling online: the patient contacts the practice
          console.log('status', now.status, '· not cancelled online; cancel until', now.cancel_until ?? '-');
        }
      } catch (err) {
        if (!(err instanceof KustiesError)) throw err;

        // Tell the patient what to do; log only the code and the request id, never the form
        switch (err.code) {
          case 'booking_slot_taken':
            console.log('That time was just taken: show the free times again.');
            break;
          case 'validation_failed':
            console.log('Check these fields:', err.fields.map((f) => `${f.field} (${f.code})`).join(', '));
            break;
          case 'booking_limit_reached':
          case 'api_daily_limit_reached':
          case 'rate_limited':
            console.log('Online booking is not possible right now; please call the practice.', err.retryAfter ?? '');
            break;
          default:
            console.log('Kusties refused:', err.status, err.code, 'request', err.requestId);
        }
      }
      

PHP, organization-flow.php (with kusties.php from §4):

<?php
      // organization-flow.php: an organisation's key with every scope, on the sandbox:
      //   KUSTIES_API_KEY=kst_test_… TEST_EMAIL=you@example.com TEST_PHONE=+37120000000 php organization-flow.php

      declare(strict_types=1);

      require __DIR__ . '/kusties.php';

      // 1. The organisation, its team, its branches and the services it offers online
      $me = kusties('GET', '/me')['data'];
      $specialists = kusties('GET', '/specialists')['data']['data'];
      $locations = kusties('GET', '/locations')['data']['data'];
      $service = kusties('GET', '/services')['data']['data'][0];
      $branch = null;
      foreach ($locations as $candidate) {
          if (in_array($candidate['id'], $service['location_ids'], true)) {
              $branch = $candidate;
              break;
          }
      }
      echo $me['account']['name'], ' · ', $service['name'], ' · ', $branch['name'], "\n";

      // 2. A free time of the service at the branch, with any specialist ('specialist_id' => one of
      //    $service['specialist_ids'] for one, 'part' => 'morning' | 'day' | 'evening' for a part of the day). Past the
      //    latest online cancelling deadline of the service's specialists, so this test can cancel what it books. Your
      //    form shows the patient every free time of the week instead.
      $hours = 0;
      foreach ($specialists as $member) {
          if (in_array($member['id'], $service['specialist_ids'], true)) {
              $hours = max($hours, $member['cancel_hours'] ?? 0);
          }
      }
      $notBefore = new DateTimeImmutable(sprintf('+%d hours', $hours + 1));
      $slot = kusties_first_free_start('/availability', ['service_id' => $service['id'], 'location_id' => $branch['id']], $notBefore, $branch['time_zone']);
      if ($slot === null) {
          throw new RuntimeException('No free time within the booking window');
      }
      echo 'free at ', $slot['start_time'], ' (', count($slot['specialist_ids']), ' free)', "\n";

      // 3. The booking: no specialist_id means any specialist free then (the least busy that week)
      $client = ['first_name' => 'Anna', 'last_name' => 'Bērziņa', 'email' => getenv('TEST_EMAIL'), 'phone' => getenv('TEST_PHONE'), 'language' => 'en'];
      if (!$client['email'] || !$client['phone']) {
          throw new LogicException('Set TEST_EMAIL and TEST_PHONE to your own address and number');
      }

      try {
          $booking = kusties_book([
              'service_id' => $service['id'],
              'start_time' => $slot['start_time'],
              'location_id' => $slot['location_id'], // the branch you showed
              'client' => $client,
              'privacy_notice_shown' => true,
          ])['data'];
          echo 'booked ', $booking['id'], ' ', $booking['status'], ' with ', $booking['specialist']['name'], ' until ', $booking['end_time'], "\n";

          // 4. Reschedule it to a later free time of the same specialist, while the specialist allows that online
          if ($booking['can_reschedule']) {
              $after = (new DateTimeImmutable($booking['start_time']))->modify('+1 minute'); // not its own start
              $other = kusties_first_free_start('/bookings/' . $booking['id'] . '/availability', [], $after, $booking['time_zone']);

              if ($other !== null) {
                  $moved = kusties('POST', '/bookings/' . $booking['id'] . '/reschedule', [], ['start_time' => $other['start_time']])['data'];
                  echo 'rescheduled to ', $moved['start_time'], "\n";
              }
          }

          // 5. The account's open bookings, page by page (the patient can also cancel or reschedule through
          //    Kusties' e-mail, so read them again before you show them)
          $cursor = null;
          do {
              $page = kusties('GET', '/bookings', ['status' => 'requested,scheduled', 'limit' => 50, 'cursor' => $cursor])['data'];
              foreach ($page['data'] as $open) {
                  echo 'open ', $open['id'], ' ', $open['status'], ' ', $open['start_time'], ' ', $open['specialist']['name'], "\n";
              }
              $cursor = $page['next_cursor'];
          } while ($cursor !== null);

          // 6. Cancel it while the specialist allows that online
          $now = kusties('GET', '/bookings/' . $booking['id'])['data'];

          if ($now['can_cancel']) {
              $cancelled = kusties('POST', '/bookings/' . $booking['id'] . '/cancel')['data'];
              echo 'status ', $cancelled['status'], "\n";
          } else {
              // Past cancel_until, or the specialist does not allow cancelling online: the patient contacts the practice
              echo 'status ', $now['status'], ' · not cancelled online; cancel until ', $now['cancel_until'] ?? '-', "\n";
          }
      } catch (KustiesError $e) {
          // Tell the patient what to do; log only the code and the request id, never the form
          echo match ($e->errorCode) {
              'booking_slot_taken' => 'That time was just taken: show the free times again.',
              'validation_failed' => 'Check these fields: ' . implode(', ', array_map(fn ($f) => $f['field'] . ' (' . $f['code'] . ')', $e->fields)),
              'booking_limit_reached', 'api_daily_limit_reached', 'rate_limited' => 'Online booking is not possible right now; please call the practice.',
              default => 'Kusties refused: ' . $e->status . ' ' . $e->errorCode . ' request ' . $e->requestId,
          }, "\n";
      }
      

6. After the booking: read, list, cancel and reschedule#

Read. GET /bookings/{id} (scope bookings:read) reads a booking the account made through the API, with any of the account's keys, so a replaced key's bookings stay readable. A booking made elsewhere (Kusties' own page, the widget, the client cabinet) or by another account answers 404 booking_not_found, as an unknown id does; so does a booking whose specialist the key does not reach, and, for an organisation, a booking whose specialist has left it.

List. GET /bookings (scope bookings:read) lists the account's bookings made through the API, with all its keys, in the order of their start: status (one, or several separated by commas), start_from (included) and start_to (not included) narrow it, limit sets the page size (1–100, default 20), and cursor asks for the next page (developer guide → Conventions).

There are no webhooks in version 1. To learn whether a request was confirmed, list the bookings that are still requested at most every 10–15 minutes, or read one when the patient opens a page that shows it. The patient can also cancel or reschedule a booking through Kusties' e-mail: read it again before you show it.

Cancel: POST /bookings/{id}/cancel (scope bookings:update, no body) while can_cancel is true: until cancel_until, the specialist's online cancelling deadline. Later, or once the visit is over: 409 booking_cancel_closed; tell the patient to contact the specialist. A booking that is already cancelled or declined answers 200 as it is, and nothing is sent again.

Reschedule: GET /bookings/{id}/availability (scope bookings:update; from and to as for /availability) gives the starts the booking can be rescheduled to: the same specialist and length (for an organisation's booking, at the organisation's branches), without its own start. POST /bookings/{id}/reschedule with {"start_time": "…"} reschedules it. It works while can_reschedule is true: until cancel_until, at most 3 times per booking (the patient's own changes count too), and only while the specialist allows it online; otherwise 409 booking_move_closed. A start that is no longer free: 409 booking_slot_taken. While the booking is open (requested or scheduled), its own start answers 200 and changes nothing, also when the same request arrives twice at once (a double click, a retry while the first is still running): both answer 200 with the booking at its new time. A cancelled, declined or past booking answers 409 booking_move_closed whatever the start, its own too. A request stays a request.

With the booking's id in ID:

# The booking (bookings:read)
      curl -sS "$BASE/bookings/$ID" -H "Authorization: Bearer $KUSTIES_API_KEY"

      # The account's open bookings that start from a moment on, 20 a page (the next page: &cursor=<next_cursor>)
      curl -sS "$BASE/bookings?status=requested,scheduled&start_from=2026-11-24T00:00:00Z" \
        -H "Authorization: Bearer $KUSTIES_API_KEY"

      # The times it can be rescheduled to (bookings:update)
      curl -sS "$BASE/bookings/$ID/availability?from=2026-11-24&to=2026-11-24" \
        -H "Authorization: Bearer $KUSTIES_API_KEY"
      

The list answer:

{
        "data": [
          {
            "id": "0d009a40-837b-4c24-8e6f-fac790897f6f",
            "status": "scheduled",
            "start_time": "2026-11-24T07:00:00Z",
            "end_time": "2026-11-24T08:00:00Z",
            "time_zone": "Europe/Riga",
            "service": {
              "id": "dab8e38f-c573-422f-ac8c-63cf078aa717",
              "name": "Konsultācija"
            },
            "specialist": {
              "id": "f147239b-c511-4afd-941e-1e9ebbbda477",
              "name": "Anna Bērziņa"
            },
            "format": "practice",
            "location": {
              "id": "f147239b-c511-4afd-941e-1e9ebbbda477",
              "address": "Tērbatas iela 14, Rīga"
            },
            "cancel_until": "2026-11-23T07:00:00Z",
            "can_cancel": true,
            "can_reschedule": true,
            "created_at": "2026-11-21T21:13:24.274764Z"
          },
          {
            "id": "97d3564d-7029-40ef-b91b-1cf1cd3a3e59",
            "status": "scheduled",
            "start_time": "2026-11-26T07:00:00Z",
            "end_time": "2026-11-26T08:30:00Z",
            "time_zone": "Europe/Riga",
            "service": {
              "id": "757f47c2-6136-4cd0-a9a6-29a060c10923",
              "name": "Mājas vizīte"
            },
            "specialist": {
              "id": "f147239b-c511-4afd-941e-1e9ebbbda477",
              "name": "Anna Bērziņa"
            },
            "format": "home",
            "location": {
              "address": "Ozolu iela 7-12, Rīga"
            },
            "cancel_until": "2026-11-25T07:00:00Z",
            "can_cancel": true,
            "can_reschedule": true,
            "created_at": "2026-11-21T21:13:24.336192Z"
          }
        ],
        "next_cursor": null
      }
      

Then, with one of the starts it can be rescheduled to in NEW:

# Reschedule it to one of those start times, then cancel it (bookings:update)
      curl -sS -X POST "$BASE/bookings/$ID/reschedule" \
        -H "Authorization: Bearer $KUSTIES_API_KEY" \
        -H "Content-Type: application/json" \
        -d "{\"start_time\": \"$NEW\"}"
      curl -sS -X POST "$BASE/bookings/$ID/cancel" -H "Authorization: Bearer $KUSTIES_API_KEY"
      

7. What the patient receives#

Kusties e-mails the patient as it does for a booking on its own page: in the booking's client.language, in the specialist's name, with replies going to the specialist. The links in them lead to Kusties, not to your website.

WhenE-mail to the patient
booked, waiting for the specialist"Your booking request has been received", with a link to cancel the request
booked and confirmed, or confirmed later"Your appointment is confirmed", with a calendar file and a link to cancel or reschedule it (while the specialist allows that online)
declined, or not answered in time"This booking time cannot be confirmed" or "Your booking request was not confirmed", with a link to the specialist's Kusties booking page
cancelled (through your website or the link)the cancellation
rescheduled"Your appointment has been moved", with the new time, a calendar file and a new link: the old one stops working
before the visitthe specialist's reminders (SMS or e-mail), as for any visit (not on the sandbox)
after the confirmationthe specialist's first-visit questionnaire, when they use it

The specialist is told of every new booking or request, cancellation and change of time, and sees in their calendar that the booking came from a website («Avots: jūsu mājaslapa», with the key's name).

8. Your website's duties#

Your website collects the patient's data before Kusties does. It acts for the specialist (or the organisation), who answers for it: agree the processing of patients' data with the account holder (GDPR Article 28). The duties of every integration, the key's safety among them, are in the developer guide; for a booking form:

  1. Show Kusties' notice before sending. Above the button that sends the booking, show the short notice «Jūsu dati» with a link to privacy_notice_url (from GET /me; never a copied address). Send privacy_notice_shown: true only when your form showed it; Kusties refuses a booking without it and stores nothing about it. The wording is the short notice for a website's booking form in Annex 3 of Kusties' data processing agreement; if Kusties changes it there, the new wording applies:

    LV: Jūsu dati. Par šeit norādītajiem datiem atbild {speciālists, pie kura pierakstāties / prakses vai speciālista nosaukums}. Šī mājaslapa jūsu vārdu, uzvārdu, tālruni, e-pasta adresi, izvēlēto vizīti un laiku, komentāru un, ja vizīte notiek jūsu mājās, adresi nosūta sistēmai Kusties (SIA "Kusties.com"), kas pierakstu apstrādā {speciālista / mūsu} uzdevumā un sūta jums e-pastus par to. Lūdzu, komentārā nerakstiet veselības informāciju; to pārrunāsiet vizītē. Ja pieprasījums netiek apstiprināts un vēl neesat {speciālista / mūsu} klients, Kusties jūsu kontaktinformāciju, komentāru un adresi dzēš pēc 90 dienām. Vairāk par datu apstrādi: {saite uz pilno informāciju, piemēram, https://kusties.com/pacientiem}.

    EN: Your data. {The specialist you book with / name of the practice or specialist} is responsible for the data you give here. This website sends your first and last name, phone, e-mail address, the visit and time you choose, your comment and, if the visit takes place at your home, your address to the Kusties system (SIA "Kusties.com"), which processes the booking on {the specialist's / our} behalf and e-mails you about it. Please don't write health information in the comment; you can discuss it at the visit. If the request is not confirmed and you are not yet {the specialist's / our} client, Kusties deletes your contact details, comment and address after 90 days. More about data processing: {link to the full information, for example https://kusties.com/en/patients}.

  2. The comment's hint. Under the comment field: «Lūdzu, nerakstiet šeit veselības informāciju; to pārrunāsiet vizītē.» (EN: "Please don't write health information here; you will discuss it at the visit.").

  3. Only bookings people make themselves. Send only people who asked to book through your form: no imports, no test bookings on live, no bookings for someone who did not ask, and none entered by staff on someone's behalf (they book in Kusties itself).

  4. Your own bot check and limits. Kusties does not see your visitors and does not run its bot check on this path; it limits each key and account. Protect your form yourself (for example Cloudflare Turnstile, hCaptcha or reCAPTCHA) and limit bookings per visitor, or one abusive visitor can use up your website's budget for everyone.

  5. No patient data in logs, analytics or error trackers: log the booking's id, the error code and the X-Request-ID instead.

9. Retries: Idempotency-Key#

A booking request can time out after Kusties has booked. To retry safely, send an Idempotency-Key header with every POST /bookings: a unique value per booking attempt (for example a UUID made when the patient presses the button), at most 120 characters. Never put personal data in it: Kusties keeps it with the booking.

  • The same Idempotency-Key and the same request from the same API key: Kusties answers 201 with the first booking and the header Idempotent-Replayed: true, and books or sends nothing again. This also holds when two copies arrive at the same moment, even when the first one is the booking that fills the account's limit of 100 a day.
  • The same Idempotency-Key with a different request (any field changed: a name, the comment, the time, the address): 409 idempotency_key_reused. When the patient changes anything, make a new Idempotency-Key.
  • Formatting does not make a request different: the e-mail's letter case, the phone written with or without +371 and spaces, spaces around a name, or the start written with another offset.
  • A request that was refused (for example 409 booking_slot_taken) booked nothing, so its Idempotency-Key can be sent again with the same request.
  • An Idempotency-Key belongs to the API key that sent it: another API key of the same account does not see it.
  • Retries are for minutes, not months: Kusties may forget a request's details (for example 90 days after a declined request), and a late retry then answers 409.

Retry only when the outcome is unknown (a timeout, a lost connection) or the answer was a 5xx; never retry a 4xx in a loop.

10. When a booking is refused#

Every code is in the developer guide. What to tell the patient when a booking, a cancel or a reschedule is refused:

codeTell the patient
validation_failedwhich field to correct (fields[].field, e.g. client.phone)
booking_slot_takenthe time was just taken: show the free times again
booking_unavailableonline booking is not available now; please contact the practice
booking_limit_reachedthis person already has the most open bookings with this specialist, or the specialist's online bookings for the day are full: please call the practice
api_daily_limit_reached, rate_limitedonline booking is not possible right now; please try later or call the practice
booking_cancel_closed, booking_move_closedit can no longer be changed online; please contact the specialist

11. The smoke test#

This script checks a key and the whole path on the sandbox: the key and its account, the specialist, the locations and a week of free times; a booking with an Idempotency-Key, its replay, a changed request (409) and a booking without the notice flag (400); the booking's status and its place in the list, a reschedule and a cancel (twice); and the refusals for an unknown booking, another specialist, a malformed cursor, no key, a malformed key and a browser's Origin. It books on the day after tomorrow (Riga time) or later, past the sandbox specialist's online cancelling deadline of 24 hours, and cancels the booking it made, also when a step fails. It needs bash, curl, jq and uuidgen, and a specialist's key with every scope.

Run it against the sandbox with your key and your own e-mail address and phone number (the e-mails reach you only if your address is on the sandbox's list): KEY=kst_test_… EMAIL=you@example.com PHONE=+37120000000 bash kusties-api-smoke.sh. It prints each step's answer and ends with smoke ok; on a failure it prints the request and Kusties' answer (with its code and request_id) to stderr and exits with 1.

#!/usr/bin/env bash
      # The Kusties API's smoke test, on the sandbox: a specialist's key with every scope reads the key, the account and a
      # week of free times, books with an Idempotency-Key (a retry is replayed, another body refused), reads and lists the
      # booking, reschedules and cancels it (a repeated cancel answers 200 too), and the refusals answer as documented. A
      # failure prints the request and Kusties' answer to stderr and exits 1; a booking it made is cancelled on the way out.
      # Run: KEY=kst_test_… EMAIL=<your address> PHONE=<your number> bash kusties-api-smoke.sh
      set -euo pipefail
      BASE=${BASE:-https://api-sandbox.kusties.app/v1}
      : "${KEY:?set KEY to your kst_test_ key}" "${EMAIL:?set EMAIL to your own address}" "${PHONE:?set PHONE to your own number}"
      case "$BASE" in https://*) ;; *) echo "FAIL: BASE must start with https://" >&2; exit 1 ;; esac
      H=(-H "Authorization: Bearer $KEY" -H "Content-Type: application/json")
      want() { local out; out=$(curl -sS -w '\n%{http_code}' "${H[@]}" "${@:2}"); [ "$(tail -n1 <<<"$out")" = "$1" ] || { echo "FAIL want $1: ${*: -1}" >&2; echo "$out" >&2; exit 1; }; sed '$d' <<<"$out"; }
      code() { curl -sS -o /dev/null -w '%{http_code}' "$@"; }
      ID=""; cleanup() { [ -n "$ID" ] && curl -sS -o /dev/null "${H[@]}" -X POST "$BASE/bookings/$ID/cancel" || true; }; trap cleanup EXIT

      want 200 "$BASE/me" | jq -c '{account: .account.type, scopes: .key.scopes, sandbox: .key.sandbox}'
      want 200 "$BASE/specialists" | jq -c '[.data[] | {name, cancel_hours}]'
      want 200 "$BASE/locations" | jq -c '[.data[] | {id, main}]'
      SERVICE=$(want 200 "$BASE/services" | jq -r '[.data[] | select(.formats | index("practice"))][0].id // empty')   # a home visit needs visit_address
      [ -n "$SERVICE" ] || { echo "FAIL: no service at the practice" >&2; exit 1; }
      DAY=$(TZ=Europe/Riga date -v+2d +%F 2>/dev/null || TZ=Europe/Riga date -d '+2 days' +%F)   # the day after tomorrow in Riga: past any cancel deadline of 24 h
      WEEK=$(want 200 "$BASE/availability?service_id=$SERVICE&from=$DAY")
      NEXT=$(jq -r '.next_available.date // empty' <<<"$WEEK")
      [ -z "$NEXT" ] || WEEK=$(want 200 "$BASE/availability?service_id=$SERVICE&from=$NEXT")   # nothing free that week: from the nearest free day
      START=$(jq -r '.slots[0].start_time // empty' <<<"$WEEK"); LOCATION=$(jq -r '.slots[0].location_id // empty' <<<"$WEEK")
      [ -n "$START" ] || { echo "FAIL: no free time from $DAY on" >&2; exit 1; }
      BODY=$(jq -nc --arg s "$SERVICE" --arg t "$START" --arg l "$LOCATION" --arg e "$EMAIL" --arg p "$PHONE" \
        '{service_id:$s,start_time:$t,location_id:(if $l == "" then null else $l end),client:{first_name:"API",last_name:"Smoke",email:$e,phone:$p,language:"lv"},privacy_notice_shown:true}')
      IDEM=$(uuidgen)
      B=$(want 201 -X POST -H "Idempotency-Key: $IDEM" -d "$BODY" "$BASE/bookings"); ID=$(jq -r .id <<<"$B"); jq -c '{id,status,start_time}' <<<"$B"
      R=$(curl -sS -D - -o /dev/null "${H[@]}" -X POST -H "Idempotency-Key: $IDEM" -d "$BODY" "$BASE/bookings")
      grep -q '^HTTP/[0-9.]* 201' <<<"$R" && grep -qi '^idempotent-replayed: true' <<<"$R" || { echo "FAIL replay" >&2; echo "$R" >&2; exit 1; }
      echo "replayed: $(grep -i '^idempotent-replayed' <<<"$R" | tr -d '\r')"
      want 409 -X POST -H "Idempotency-Key: $IDEM" -d "$(jq -c '.client.first_name="Other"' <<<"$BODY")" "$BASE/bookings" | jq -r .code   # idempotency_key_reused
      want 400 -X POST -d "$(jq -c '.privacy_notice_shown=false' <<<"$BODY")" "$BASE/bookings" | jq -c '{code, fields: [.fields[].field]}'   # validation_failed
      want 200 "$BASE/bookings/$ID" | jq -c '{status,can_cancel,can_reschedule,cancel_until}'
      want 200 "$BASE/bookings?status=requested,scheduled&start_from=$START&limit=100" | jq -e --arg id "$ID" 'any(.data[]; .id == $id)' >/dev/null || { echo "FAIL: the booking is not listed" >&2; exit 1; }
      echo "listed: $ID"
      NEW=$(want 200 "$BASE/bookings/$ID/availability?from=$DAY" | jq -r '.slots[0].start_time // empty')   # its own start is left out
      [ -z "$NEW" ] || want 200 -X POST -d "$(jq -nc --arg s "$NEW" '{start_time:$s}')" "$BASE/bookings/$ID/reschedule" | jq -c '{status,start_time}'
      want 200 -X POST "$BASE/bookings/$ID/cancel" | jq -r .status      # cancelled
      want 200 -X POST "$BASE/bookings/$ID/cancel" | jq -r .status      # repeat: 200, nothing sent
      ID=""
      want 404 "$BASE/bookings/$(uuidgen | tr 'A-Z' 'a-z')" | jq -r .code                                       # booking_not_found
      want 403 "$BASE/availability?service_id=$SERVICE&specialist_id=$(uuidgen | tr 'A-Z' 'a-z')" | jq -r .code   # api_key_specialist_not_allowed
      want 400 "$BASE/bookings?cursor=not-a-cursor" | jq -c '{code, fields: [.fields[] | .field + "/" + .code]}'   # validation_failed
      [ "$(code "$BASE/me")" = 401 ] || { echo "FAIL: no key" >&2; exit 1; }
      [ "$(code -H 'Authorization: Bearer kst_test_short' "$BASE/me")" = 401 ] || { echo "FAIL: a malformed key" >&2; exit 1; }
      want 403 -H 'Origin: https://website.example' "$BASE/me" | jq -r .code                                     # api_browser_not_allowed
      echo "smoke ok"
      
Kusties

Exercise programmes that patients actually do. Built for physiotherapists, coaches and clinics.

Product

  • Home page (in Latvian)
  • Pricing (in Latvian)
  • Developers
  • Create your first programme

Solutions (in Latvian)

  • Physiotherapists
  • Clinics and medical centres
  • Personal trainers
  • Clients and patients

Contact

  • info@kusties.com
  • +371 22 322 885
  • Log in

Legal

  • Security
  • Terms of Service
  • Privacy Policy
  • Data Processing Agreement
  • For patients
  • Client cabinet terms
  • Latviski

© 2026 Kusties. All rights reserved.

SIA “Kusties.com”, reg. No. 50203259371, VAT LV50203259371, Ābolu iela 14C, Mārupe, Mārupes nov., LV-2167