Book a visit with a dietitian
Write a command-line program that connects a patient, checks for a saved card, books a visit with a dietitian, shows it and cancels it.
You build a command-line program for the whole path of one patient: create the patient, wait for the patient to approve, save a card, book a visit, read it and cancel it. Each step is a command, such as create or book. You run them one at a time, because a person must approve in a browser between some steps.
The API calls a dietitian a specialist. It calls a visit a booking. The code uses the API's words. The text says dietitian and visit.
Before you start#
- You finished Set up your project. Your project has the
nurishdclient file and a Sandbox key inNURISHD_API_KEY. - Your key has the scopes
patient:write,booking:write,booking:readandspecialist:read. Run the key check from the setup tutorial to see your scopes. - Your company has a signed BAA, a business associate agreement with Nurish'd. Care scopes need it. Without it every care call answers
403 scope_not_granted. See BAA handling. - A web browser, and a web page of yours that can load Stripe.js. Step 4 explains why.
The patient in this tutorial is the fake Ada Lovelace at an example address. The Sandbox takes fake people only.
Two guides explain the same routes in detail: Connecting a patient and Booking a visit. This page links to them instead of repeating them.
1. Keep the ids between commands#
Each command runs and ends. The next command needs the patient id, the connection id and later the booking id. The program saves them in a small file, visit-state.json. A real app keeps them in its database.
The program also fixes the patient's province and time zone at the top. A dietitian must be licensed where the patient lives, so the program asks only for dietitians in ON.
import json
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from nurishd import NurishdError, call
STATE_FILE = Path("visit-state.json")
PATIENT_STATE = "ON"
PATIENT_TIMEZONE = "America/Toronto"
HINTS = {
"connection_not_active": "The patient has not approved yet, or the connection ended. Run status.",
"connection_scope_not_granted": "The patient did not allow bookings. Create the patient again with a key that holds booking:write.",
"scope_not_granted": "Your key lacks a scope, or your company has no signed BAA.",
"agreements_not_signed": "The patient has not signed the agreements. Run create again and send them the new link.",
"payment_method_required": "The patient has no saved card. Run card, finish it in a browser, then book again.",
"not_licensed_here": "This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
"service_not_bookable": "This service cannot be booked online. Choose another service.",
"slot_taken": "The time is no longer open. Run book again to find a new one.",
"booking_not_cancelable": "The booking is already canceled, completed or past.",
"validation_error": "A field is wrong. In client_note, do not use $, { or }.",
}
STATE_FILE = Path("visit-state.json")
PATIENT_STATE = "ON"
PATIENT_TIMEZONE = "America/Toronto"
def load_state():
if not STATE_FILE.exists():
sys.exit("There is no saved patient yet. Run create first.")
return json.loads(STATE_FILE.read_text())
def load_booking_id(state):
if "booking_id" not in state:
sys.exit("There is no booking yet. Run book first.")
return state["booking_id"]
def save_state(state):
STATE_FILE.write_text(json.dumps(state, indent=2))import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { NurishdError, call } from './nurishd.js';
const STATE_FILE = 'visit-state.json';
const PATIENT_STATE = 'ON';
const PATIENT_TIMEZONE = 'America/Toronto';
const HINTS = {
connection_not_active:
'The patient has not approved yet, or the connection ended. Run status.',
connection_scope_not_granted:
'The patient did not allow bookings. Create the patient again with a key that holds booking:write.',
scope_not_granted:
'Your key lacks a scope, or your company has no signed BAA.',
agreements_not_signed:
'The patient has not signed the agreements. Run create again and send them the new link.',
payment_method_required:
'The patient has no saved card. Run card, finish it in a browser, then book again.',
not_licensed_here:
"This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
service_not_bookable:
'This service cannot be booked online. Choose another service.',
slot_taken: 'The time is no longer open. Run book again to find a new one.',
booking_not_cancelable:
'The booking is already canceled, completed or past.',
validation_error: 'A field is wrong. In client_note, do not use $, { or }.',
};
const STATE_FILE = 'visit-state.json';
const PATIENT_STATE = 'ON';
const PATIENT_TIMEZONE = 'America/Toronto';
function loadState() {
if (!existsSync(STATE_FILE)) {
exitWith('There is no saved patient yet. Run create first.');
}
return JSON.parse(readFileSync(STATE_FILE, 'utf8'));
}
function loadBookingId(state) {
if (!state.booking_id) exitWith('There is no booking yet. Run book first.');
return state.booking_id;
}
function saveState(state) {
writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
}import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { NurishdError, call } from './nurishd.ts';
import type { Page } from './nurishd.ts';
const STATE_FILE = 'visit-state.json';
const PATIENT_STATE = 'ON';
const PATIENT_TIMEZONE = 'America/Toronto';
function loadState(): State {
if (!existsSync(STATE_FILE)) {
exitWith('There is no saved patient yet. Run create first.');
}
return JSON.parse(readFileSync(STATE_FILE, 'utf8'));
}
function loadBookingId(state: State): string {
if (!state.booking_id) exitWith('There is no booking yet. Run book first.');
return state.booking_id;
}
function saveState(state: State) {
writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
}package tutorial;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import tutorial.Nurishd.NurishdException;
static final Path STATE_FILE = Path.of("visit-state.json");
static final String PATIENT_STATE = "ON";
static final String PATIENT_TIMEZONE = "America/Toronto";
static ObjectNode loadState() throws IOException {
if (!Files.exists(STATE_FILE)) {
exitWith("There is no saved patient yet. Run create first.");
}
return (ObjectNode) Nurishd.JSON.readTree(Files.readString(STATE_FILE));
}
static String loadBookingId(ObjectNode state) {
if (!state.has("booking_id")) {
exitWith("There is no booking yet. Run book first.");
}
return state.get("booking_id").asText();
}
static void saveState(ObjectNode state) throws IOException {
Files.writeString(STATE_FILE, Nurishd.JSON.writerWithDefaultPrettyPrinter().writeValueAsString(state));
}2. Create the patient and send them to approve#
POST /care/v1/patient/create/document creates the patient and starts a connection. A connection is the patient's consent for your company to act for them. See Connections.
The body needs external_id (your own id for the patient), email, first_name, last_name, date_of_birth and address. The address has been required since 2026-11-18. A dietitian must be licensed where the patient lives, so a visit cannot be booked for a patient with no address. A call without an address answers 422 validation_error.
The answer has the patient's id in user, the connection in connection, and a connect_url. The program saves the ids and prints the link.
def create_patient():
patient = call(
"POST",
"/care/v1/patient/create/document",
body={
"external_id": "tutorial-patient-1",
"email": "ada.lovelace@example.com",
"first_name": "Ada",
"last_name": "Lovelace",
"date_of_birth": "1990-12-10",
"address": {
"line1": "10 Example Street",
"city": "Toronto",
"state": PATIENT_STATE,
"postal_code": "M5V 2T6",
"country": "CA",
},
},
)
save_state(
{
"patient_id": patient["user"],
"connection_id": patient["connection"]["connection_id"],
}
)
print("Open this link in a browser and approve the connection:")
print(patient["connect_url"])async function createPatient() {
const patient = await call('POST', '/care/v1/patient/create/document', {
body: {
external_id: 'tutorial-patient-1',
email: 'ada.lovelace@example.com',
first_name: 'Ada',
last_name: 'Lovelace',
date_of_birth: '1990-12-10',
address: {
line1: '10 Example Street',
city: 'Toronto',
state: PATIENT_STATE,
postal_code: 'M5V 2T6',
country: 'CA',
},
},
});
saveState({
patient_id: patient.user,
connection_id: patient.connection.connection_id,
});
console.log('Open this link in a browser and approve the connection:');
console.log(patient.connect_url);
}async function createPatient() {
const patient = await call<Patient>(
'POST',
'/care/v1/patient/create/document',
{
body: {
external_id: 'tutorial-patient-1',
email: 'ada.lovelace@example.com',
first_name: 'Ada',
last_name: 'Lovelace',
date_of_birth: '1990-12-10',
address: {
line1: '10 Example Street',
city: 'Toronto',
state: PATIENT_STATE,
postal_code: 'M5V 2T6',
country: 'CA',
},
},
},
);
saveState({
patient_id: patient.user,
connection_id: patient.connection.connection_id,
});
console.log('Open this link in a browser and approve the connection:');
console.log(patient.connect_url);
}static void createPatient() throws IOException {
Map<String, Object> address = Map.of(
"line1", "10 Example Street",
"city", "Toronto",
"state", PATIENT_STATE,
"postal_code", "M5V 2T6",
"country", "CA");
Map<String, Object> body = Map.of(
"external_id", "tutorial-patient-1",
"email", "ada.lovelace@example.com",
"first_name", "Ada",
"last_name", "Lovelace",
"date_of_birth", "1990-12-10",
"address", address);
JsonNode patient = Nurishd.call("POST", "/care/v1/patient/create/document", Map.of(), body);
ObjectNode state = Nurishd.JSON.createObjectNode();
state.put("patient_id", patient.path("user").asText());
state.put("connection_id", patient.path("connection").path("connection_id").asText());
saveState(state);
System.out.println("Open this link in a browser and approve the connection:");
System.out.println(patient.path("connect_url").asText());
}To send the patient back to your site after the approval page, add return_url to the body. It must be one of the return URLs you registered in the console. The program leaves it out.
Run the command. Replace python visit.py with the command of your language.
- Python:
python visit.py create - JavaScript:
node visit.js create - TypeScript:
node visit.ts create - Java:
mvn -q compile exec:java -Dexec.mainClass=tutorial.Visit -Dexec.args="create"
Open this link in a browser and approve the connection:
https://app.nurishd.ca/connect/abc1233. Approve in a browser, then check the status#
Open the link in a browser, as a full page or a new tab. Never put it in a frame or a web view. The link works once and stays valid for 24 hours.
On the page the patient enters a code, signs the health privacy agreement and the telehealth consent if they are not signed yet, and approves. In the Sandbox no email is sent. Enter the fixed code 424242.
Now read the connection with GET /care/v1/connection/{connection_id}/get/document. Continue only when the status is active. A pending connection means the patient has not decided. See Connecting a patient for the other statuses.
def show_status():
state = load_state()
path = f"/care/v1/connection/{state['connection_id']}/get/document"
connection = call("GET", path)
print(f"Connection status: {connection['status']}")
if connection["status"] != "active":
print("The patient has not approved yet. Run status again later.")async function showStatus() {
const state = loadState();
const path = `/care/v1/connection/${state.connection_id}/get/document`;
const connection = await call('GET', path);
console.log(`Connection status: ${connection.status}`);
if (connection.status !== 'active') {
console.log(
'The patient has not approved yet. Run status again later.',
);
}
}async function showStatus() {
const state = loadState();
const path = `/care/v1/connection/${state.connection_id}/get/document`;
const connection = await call<{ status: string }>('GET', path);
console.log(`Connection status: ${connection.status}`);
if (connection.status !== 'active') {
console.log(
'The patient has not approved yet. Run status again later.',
);
}
}static void showStatus() throws IOException {
ObjectNode state = loadState();
String path = "/care/v1/connection/%s/get/document".formatted(state.get("connection_id").asText());
JsonNode connection = Nurishd.call("GET", path);
System.out.println("Connection status: " + connection.path("status").asText());
if (!connection.path("status").asText().equals("active")) {
System.out.println("The patient has not approved yet. Run status again later.");
}
}python visit.py status
Connection status: pending
The patient has not approved yet. Run status again later.After you approve in the browser, run it again:
python visit.py status
Connection status: active4. Save a card#
A visit needs a saved card. Booking charges nothing. The visit, a late-cancellation fee and a no-show fee are charged later to the patient's default card. A patient made through your company has no card, so booking answers 409 payment_method_required and books nothing. Tell the patient their card may be charged before they type it in.
Saving a card has three parts:
- Your server starts a setup with
POST /care/v1/patient/{patient_id}/payment-method/setup/create/document. The answer holds aclient_secretand a Stripe publishable key. - In the patient's browser, your page gives both to Stripe.js. The patient types the card into Stripe's own form. The card number never reaches your server.
- Your server records the card with
PUT /care/v1/patient/{patient_id}/payment-method/setup/{setup_id}/confirm/document.
Parts 2 and 3 need a web page, so this tutorial does not copy them. Follow Saving a card. In the Sandbox, use a Stripe test card.
The program has the server side of part 1, and a command that lists the saved cards with GET /care/v1/patient/{patient_id}/payment-method/query/documents. It never prints the client_secret.
def start_card_setup():
state = load_state()
path = f"/care/v1/patient/{state['patient_id']}/payment-method/setup/create/document"
setup = call("POST", path)
print(f"Card setup {setup['id']} started. Its status is {setup['status']}.")
print("Finish it in a browser, as the Saving a card guide shows.")
def list_cards():
state = load_state()
path = f"/care/v1/patient/{state['patient_id']}/payment-method/query/documents"
cards = call("GET", path)
if not cards["data"]:
print("No card is saved yet.")
for item in cards["data"]:
card = item["card"]
mark = " (default)" if item["is_default"] else ""
print(f"{card['brand']} ending {card['last4']}{mark}")async function startCardSetup() {
const state = loadState();
const path = `/care/v1/patient/${state.patient_id}/payment-method/setup/create/document`;
const setup = await call('POST', path);
console.log(
`Card setup ${setup.id} started. Its status is ${setup.status}.`,
);
console.log('Finish it in a browser, as the Saving a card guide shows.');
}
async function listCards() {
const state = loadState();
const path = `/care/v1/patient/${state.patient_id}/payment-method/query/documents`;
const cards = await call('GET', path);
if (cards.data.length === 0) console.log('No card is saved yet.');
for (const item of cards.data) {
const mark = item.is_default ? ' (default)' : '';
console.log(`${item.card.brand} ending ${item.card.last4}${mark}`);
}
}async function startCardSetup() {
const state = loadState();
const path = `/care/v1/patient/${state.patient_id}/payment-method/setup/create/document`;
const setup = await call<{ id: string; status: string }>('POST', path);
console.log(
`Card setup ${setup.id} started. Its status is ${setup.status}.`,
);
console.log('Finish it in a browser, as the Saving a card guide shows.');
}
async function listCards() {
const state = loadState();
const path = `/care/v1/patient/${state.patient_id}/payment-method/query/documents`;
const cards = await call<
Page<{
card: { brand: string; last4: string };
is_default: boolean;
}>
>('GET', path);
if (cards.data.length === 0) console.log('No card is saved yet.');
for (const item of cards.data) {
const mark = item.is_default ? ' (default)' : '';
console.log(`${item.card.brand} ending ${item.card.last4}${mark}`);
}
}static void startCardSetup() throws IOException {
ObjectNode state = loadState();
String path = "/care/v1/patient/%s/payment-method/setup/create/document"
.formatted(state.get("patient_id").asText());
JsonNode setup = Nurishd.call("POST", path);
System.out.println("Card setup " + setup.path("id").asText() + " started. Its status is "
+ setup.path("status").asText() + ".");
System.out.println("Finish it in a browser, as the Saving a card guide shows.");
}
static void listCards() throws IOException {
ObjectNode state = loadState();
String path = "/care/v1/patient/%s/payment-method/query/documents"
.formatted(state.get("patient_id").asText());
JsonNode cards = Nurishd.call("GET", path);
if (cards.path("data").isEmpty()) {
System.out.println("No card is saved yet.");
}
for (JsonNode item : cards.path("data")) {
String mark = item.path("is_default").asBoolean() ? " (default)" : "";
System.out.println(item.path("card").path("brand").asText() + " ending "
+ item.path("card").path("last4").asText() + mark);
}
}python visit.py card
Card setup seti_example started. Its status is requires_payment_method.
Finish it in a browser, as the Saving a card guide shows.After the browser part and the confirm call, list the cards:
python visit.py cards
visa ending 4242 (default)5. Book a visit#
POST /care/v1/booking/create/document needs these fields:
| Field | What to send |
|---|---|
user | The patient id from step 2. |
specialist_id | The dietitian's id. |
service_id | The service's id. |
start_time | The start_time of an open time, unchanged. |
timezone | The patient's time zone, such as America/Toronto. |
client_note | Optional. A note for the dietitian, at most 2000 characters. It cannot contain $, { or }. |
The dietitian, the service and the open time come from three read calls: list dietitians, list their services, read the open times of a service. The tutorial Show dietitians and their open times explains them and shows how to display them. Here the function find_open_time takes the first open time in the next 14 days. A real app lets the patient choose.
A service that cannot be booked online answers 409 service_not_bookable when you ask for its open times. The function skips it.
def utc_text(moment):
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
def find_open_time():
"""Returns the first open time as (specialist_id, service_id, start_time), or None."""
start = datetime.now(timezone.utc)
window = {"from": utc_text(start), "to": utc_text(start + timedelta(days=14))}
people = call(
"GET",
"/care/v1/specialist/query/documents",
params={"type": "Dietitian", "state": PATIENT_STATE, "size": 10},
)
for person in people["data"]:
specialist_id = person["specialist_id"]
path = f"/care/v1/specialist/{specialist_id}/service/query/documents"
for service in call("GET", path)["data"]:
service_id = service["service_id"]
path = (
f"/care/v1/specialist/{specialist_id}/service/{service_id}"
"/availability/query/documents"
)
try:
times = call("GET", path, params=window)
except NurishdError as error:
if error.code == "service_not_bookable":
continue
raise
if times.get("slots"):
return specialist_id, service_id, times["slots"][0]["start_time"]
return None
def book_visit():
state = load_state()
found = find_open_time()
if found is None:
print("No open time in the next 14 days.")
return
specialist_id, service_id, start_time = found
booking = call(
"POST",
"/care/v1/booking/create/document",
body={
"user": state["patient_id"],
"specialist_id": specialist_id,
"service_id": service_id,
"start_time": start_time,
"timezone": PATIENT_TIMEZONE,
"client_note": "I would like to talk about meal planning.",
},
)
state["booking_id"] = booking["booking_id"]
save_state(state)
print(f"Booked {booking['booking_name']} ({booking['booking_id']}).")
print(f"It starts at {booking['start_date']} (UTC). Status: {booking['status']}.")async function findOpenTime() {
const start = new Date();
const end = new Date(start.getTime() + 14 * 24 * 60 * 60 * 1000);
const window = { from: start.toISOString(), to: end.toISOString() };
const people = await call('GET', '/care/v1/specialist/query/documents', {
params: { type: 'Dietitian', state: PATIENT_STATE, size: 10 },
});
for (const person of people.data) {
const specialistId = person.specialist_id;
const path = `/care/v1/specialist/${specialistId}/service/query/documents`;
const services = await call('GET', path);
for (const service of services.data) {
const serviceId = service.service_id;
const timesPath =
`/care/v1/specialist/${specialistId}/service/${serviceId}` +
'/availability/query/documents';
let times;
try {
times = await call('GET', timesPath, { params: window });
} catch (error) {
if (
error instanceof NurishdError &&
error.code === 'service_not_bookable'
) {
continue;
}
throw error;
}
if (times.slots && times.slots.length > 0) {
return {
specialistId,
serviceId,
startTime: times.slots[0].start_time,
};
}
}
}
return null;
}
async function bookVisit() {
const state = loadState();
const found = await findOpenTime();
if (found === null) {
console.log('No open time in the next 14 days.');
return;
}
const booking = await call('POST', '/care/v1/booking/create/document', {
body: {
user: state.patient_id,
specialist_id: found.specialistId,
service_id: found.serviceId,
start_time: found.startTime,
timezone: PATIENT_TIMEZONE,
client_note: 'I would like to talk about meal planning.',
},
});
state.booking_id = booking.booking_id;
saveState(state);
console.log(`Booked ${booking.booking_name} (${booking.booking_id}).`);
console.log(
`It starts at ${booking.start_date} (UTC). Status: ${booking.status}.`,
);
}async function findOpenTime(): Promise<OpenTime | null> {
const start = new Date();
const end = new Date(start.getTime() + 14 * 24 * 60 * 60 * 1000);
const window = { from: start.toISOString(), to: end.toISOString() };
const people = await call<Page<{ specialist_id: string }>>(
'GET',
'/care/v1/specialist/query/documents',
{ params: { type: 'Dietitian', state: PATIENT_STATE, size: 10 } },
);
for (const person of people.data) {
const specialistId = person.specialist_id;
const path = `/care/v1/specialist/${specialistId}/service/query/documents`;
const services = await call<Page<{ service_id: string }>>('GET', path);
for (const service of services.data) {
const serviceId = service.service_id;
const timesPath =
`/care/v1/specialist/${specialistId}/service/${serviceId}` +
'/availability/query/documents';
let times: Times;
try {
times = await call<Times>('GET', timesPath, { params: window });
} catch (error) {
if (
error instanceof NurishdError &&
error.code === 'service_not_bookable'
) {
continue;
}
throw error;
}
if (times.slots && times.slots.length > 0) {
return {
specialistId,
serviceId,
startTime: times.slots[0].start_time,
};
}
}
}
return null;
}
async function bookVisit() {
const state = loadState();
const found = await findOpenTime();
if (found === null) {
console.log('No open time in the next 14 days.');
return;
}
const booking = await call<Booking>(
'POST',
'/care/v1/booking/create/document',
{
body: {
user: state.patient_id,
specialist_id: found.specialistId,
service_id: found.serviceId,
start_time: found.startTime,
timezone: PATIENT_TIMEZONE,
client_note: 'I would like to talk about meal planning.',
},
},
);
state.booking_id = booking.booking_id;
saveState(state);
console.log(`Booked ${booking.booking_name} (${booking.booking_id}).`);
console.log(
`It starts at ${booking.start_date} (UTC). Status: ${booking.status}.`,
);
}static String[] findOpenTime() {
Instant start = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Map<String, Object> window =
Map.of("from", start.toString(), "to", start.plus(14, ChronoUnit.DAYS).toString());
JsonNode people = Nurishd.call(
"GET",
"/care/v1/specialist/query/documents",
Map.of("type", "Dietitian", "state", PATIENT_STATE, "size", 10),
null);
for (JsonNode person : people.path("data")) {
String specialistId = person.path("specialist_id").asText();
String path = "/care/v1/specialist/%s/service/query/documents".formatted(specialistId);
for (JsonNode service : Nurishd.call("GET", path).path("data")) {
String serviceId = service.path("service_id").asText();
String timesPath = "/care/v1/specialist/%s/service/%s/availability/query/documents"
.formatted(specialistId, serviceId);
JsonNode times;
try {
times = Nurishd.call("GET", timesPath, window, null);
} catch (NurishdException error) {
if (error.code.equals("service_not_bookable")) {
continue;
}
throw error;
}
if (!times.path("slots").isEmpty()) {
String startTime = times.path("slots").get(0).path("start_time").asText();
return new String[] {specialistId, serviceId, startTime};
}
}
}
return null;
}
static void bookVisit() throws IOException {
ObjectNode state = loadState();
String[] found = findOpenTime();
if (found == null) {
System.out.println("No open time in the next 14 days.");
return;
}
Map<String, Object> body = Map.of(
"user", state.get("patient_id").asText(),
"specialist_id", found[0],
"service_id", found[1],
"start_time", found[2],
"timezone", PATIENT_TIMEZONE,
"client_note", "I would like to talk about meal planning.");
JsonNode booking = Nurishd.call("POST", "/care/v1/booking/create/document", Map.of(), body);
state.put("booking_id", booking.path("booking_id").asText());
saveState(state);
System.out.println("Booked " + booking.path("booking_name").asText() + " ("
+ booking.path("booking_id").asText() + ").");
System.out.println("It starts at " + booking.path("start_date").asText()
+ " (UTC). Status: " + booking.path("status").asText() + ".");
}python visit.py book
Booked Initial consult with Maya Okafor (booking-0001).
It starts at 2026-11-19T18:00:00Z (UTC). Status: booked.The visit is booked. These are the statuses a booking can have:
| Status | What it means |
|---|---|
booked | The visit is scheduled. |
meeting_rescheduled | The visit was moved to another time. |
meeting_completed | The visit took place. |
meeting_cancelled | The visit was canceled. |
no_show | The patient did not attend. A no-show fee can be charged to the patient's default card. |
Booking the same patient, specialist and start time again returns the first booking and creates nothing new. So if a call times out, run it again. Run book a second time to see it:
python visit.py book
Booked Initial consult with Maya Okafor (booking-0001).
It starts at 2026-11-19T18:00:00Z (UTC). Status: booked.6. Read the booking#
GET /care/v1/booking/{booking_id}/get/document returns one booking. GET /care/v1/booking/query/documents returns the visits your company booked. The patient filter keeps the visits of one patient. The list leaves out client_note.
def show_bookings():
state = load_state()
booking_id = load_booking_id(state)
booking = call("GET", f"/care/v1/booking/{booking_id}/get/document")
print(f"{booking['booking_name']}: {booking['status']}, starts {booking['start_date']}")
answer = call(
"GET",
"/care/v1/booking/query/documents",
params={"patient": state["patient_id"]},
)
print(f"Visits booked for this patient: {answer['total']}")
for item in answer["data"]:
print(f" {item['booking_id']}: {item['status']}, starts {item['start_date']}")async function showBookings() {
const state = loadState();
const bookingId = loadBookingId(state);
const booking = await call(
'GET',
`/care/v1/booking/${bookingId}/get/document`,
);
console.log(
`${booking.booking_name}: ${booking.status}, starts ${booking.start_date}`,
);
const answer = await call('GET', '/care/v1/booking/query/documents', {
params: { patient: state.patient_id },
});
console.log(`Visits booked for this patient: ${answer.total}`);
for (const item of answer.data) {
console.log(
` ${item.booking_id}: ${item.status}, starts ${item.start_date}`,
);
}
}async function showBookings() {
const state = loadState();
const bookingId = loadBookingId(state);
const booking = await call<Booking>(
'GET',
`/care/v1/booking/${bookingId}/get/document`,
);
console.log(
`${booking.booking_name}: ${booking.status}, starts ${booking.start_date}`,
);
const answer = await call<Page<Booking>>(
'GET',
'/care/v1/booking/query/documents',
{ params: { patient: state.patient_id } },
);
console.log(`Visits booked for this patient: ${answer.total}`);
for (const item of answer.data) {
console.log(
` ${item.booking_id}: ${item.status}, starts ${item.start_date}`,
);
}
}static void showBookings() throws IOException {
ObjectNode state = loadState();
String bookingId = loadBookingId(state);
JsonNode booking = Nurishd.call("GET", "/care/v1/booking/%s/get/document".formatted(bookingId));
System.out.println(booking.path("booking_name").asText() + ": " + booking.path("status").asText()
+ ", starts " + booking.path("start_date").asText());
JsonNode answer = Nurishd.call(
"GET",
"/care/v1/booking/query/documents",
Map.of("patient", state.get("patient_id").asText()),
null);
System.out.println("Visits booked for this patient: " + answer.path("total").asInt());
for (JsonNode item : answer.path("data")) {
System.out.println(" " + item.path("booking_id").asText() + ": "
+ item.path("status").asText() + ", starts " + item.path("start_date").asText());
}
}python visit.py show
Initial consult with Maya Okafor: booked, starts 2026-11-19T18:00:00Z
Visits booked for this patient: 1
booking-0001: booked, starts 2026-11-19T18:00:00Z7. Cancel the booking#
PUT /care/v1/booking/{booking_id}/cancel/document cancels a visit your company booked. The body is optional. The program sends a reason, at most 1000 characters. A booking that is already canceled, completed or past answers 409 booking_not_cancelable.
def cancel_booking():
booking_id = load_booking_id(load_state())
booking = call(
"PUT",
f"/care/v1/booking/{booking_id}/cancel/document",
body={"reason": "The patient asked to cancel."},
)
print(f"Booking {booking['booking_id']} is now {booking['status']}.")async function cancelBooking() {
const bookingId = loadBookingId(loadState());
const booking = await call(
'PUT',
`/care/v1/booking/${bookingId}/cancel/document`,
{ body: { reason: 'The patient asked to cancel.' } },
);
console.log(`Booking ${booking.booking_id} is now ${booking.status}.`);
}async function cancelBooking() {
const bookingId = loadBookingId(loadState());
const booking = await call<Booking>(
'PUT',
`/care/v1/booking/${bookingId}/cancel/document`,
{ body: { reason: 'The patient asked to cancel.' } },
);
console.log(`Booking ${booking.booking_id} is now ${booking.status}.`);
}static void cancelBooking() throws IOException {
String bookingId = loadBookingId(loadState());
JsonNode booking = Nurishd.call(
"PUT",
"/care/v1/booking/%s/cancel/document".formatted(bookingId),
Map.of(),
Map.of("reason", "The patient asked to cancel."));
System.out.println("Booking " + booking.path("booking_id").asText() + " is now "
+ booking.path("status").asText() + ".");
}python visit.py cancel
Booking booking-0001 is now meeting_cancelled.Run it again to see the refusal:
python visit.py cancel
The API answered 409 booking_not_cancelable (request req-0001).
The booking is already canceled, completed or past.8. Explain the refusals#
The last part runs the command and catches an error answer. It prints the status, the code and the request_id, then a hint for the codes you meet in this tutorial. Branch on code, never on the message. Send the request_id to support if you need help.
HINTS = {
"connection_not_active": "The patient has not approved yet, or the connection ended. Run status.",
"connection_scope_not_granted": "The patient did not allow bookings. Create the patient again with a key that holds booking:write.",
"scope_not_granted": "Your key lacks a scope, or your company has no signed BAA.",
"agreements_not_signed": "The patient has not signed the agreements. Run create again and send them the new link.",
"payment_method_required": "The patient has no saved card. Run card, finish it in a browser, then book again.",
"not_licensed_here": "This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
"service_not_bookable": "This service cannot be booked online. Choose another service.",
"slot_taken": "The time is no longer open. Run book again to find a new one.",
"booking_not_cancelable": "The booking is already canceled, completed or past.",
"validation_error": "A field is wrong. In client_note, do not use $, { or }.",
}
COMMANDS = {
"create": create_patient,
"status": show_status,
"card": start_card_setup,
"cards": list_cards,
"book": book_visit,
"show": show_bookings,
"cancel": cancel_booking,
}
def main():
if len(sys.argv) != 2 or sys.argv[1] not in COMMANDS:
print("Usage: python visit.py " + "|".join(COMMANDS))
sys.exit(1)
try:
COMMANDS[sys.argv[1]]()
except NurishdError as error:
print(f"The API answered {error.status} {error.code} (request {error.request_id}).")
print(HINTS.get(error.code, "See the Errors page for this code."))
sys.exit(1)const HINTS = {
connection_not_active:
'The patient has not approved yet, or the connection ended. Run status.',
connection_scope_not_granted:
'The patient did not allow bookings. Create the patient again with a key that holds booking:write.',
scope_not_granted:
'Your key lacks a scope, or your company has no signed BAA.',
agreements_not_signed:
'The patient has not signed the agreements. Run create again and send them the new link.',
payment_method_required:
'The patient has no saved card. Run card, finish it in a browser, then book again.',
not_licensed_here:
"This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
service_not_bookable:
'This service cannot be booked online. Choose another service.',
slot_taken: 'The time is no longer open. Run book again to find a new one.',
booking_not_cancelable:
'The booking is already canceled, completed or past.',
validation_error: 'A field is wrong. In client_note, do not use $, { or }.',
};
const COMMANDS = {
create: createPatient,
status: showStatus,
card: startCardSetup,
cards: listCards,
book: bookVisit,
show: showBookings,
cancel: cancelBooking,
};
async function main() {
const command = COMMANDS[process.argv[2]];
if (!command) {
exitWith(`Usage: node visit.js ${Object.keys(COMMANDS).join('|')}`);
}
try {
await command();
} catch (error) {
if (!(error instanceof NurishdError)) throw error;
console.log(
`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
);
console.log(HINTS[error.code] ?? 'See the Errors page for this code.');
process.exit(1);
}
}const HINTS: Record<string, string> = {
connection_not_active:
'The patient has not approved yet, or the connection ended. Run status.',
connection_scope_not_granted:
'The patient did not allow bookings. Create the patient again with a key that holds booking:write.',
scope_not_granted:
'Your key lacks a scope, or your company has no signed BAA.',
agreements_not_signed:
'The patient has not signed the agreements. Run create again and send them the new link.',
payment_method_required:
'The patient has no saved card. Run card, finish it in a browser, then book again.',
not_licensed_here:
"This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
service_not_bookable:
'This service cannot be booked online. Choose another service.',
slot_taken: 'The time is no longer open. Run book again to find a new one.',
booking_not_cancelable:
'The booking is already canceled, completed or past.',
validation_error: 'A field is wrong. In client_note, do not use $, { or }.',
};
const COMMANDS = {
create: createPatient,
status: showStatus,
card: startCardSetup,
cards: listCards,
book: bookVisit,
show: showBookings,
cancel: cancelBooking,
};
async function main() {
const command = COMMANDS[process.argv[2] as keyof typeof COMMANDS];
if (!command) {
exitWith(`Usage: node visit.js ${Object.keys(COMMANDS).join('|')}`);
}
try {
await command();
} catch (error) {
if (!(error instanceof NurishdError)) throw error;
console.log(
`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
);
console.log(HINTS[error.code] ?? 'See the Errors page for this code.');
process.exit(1);
}
}static final Map<String, String> HINTS = Map.of(
"connection_not_active",
"The patient has not approved yet, or the connection ended. Run status.",
"connection_scope_not_granted",
"The patient did not allow bookings. Create the patient again with a key that holds booking:write.",
"scope_not_granted",
"Your key lacks a scope, or your company has no signed BAA.",
"agreements_not_signed",
"The patient has not signed the agreements. Run create again and send them the new link.",
"payment_method_required",
"The patient has no saved card. Run card, finish it in a browser, then book again.",
"not_licensed_here",
"This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
"service_not_bookable",
"This service cannot be booked online. Choose another service.",
"slot_taken",
"The time is no longer open. Run book again to find a new one.",
"booking_not_cancelable",
"The booking is already canceled, completed or past.",
"validation_error",
"A field is wrong. In client_note, do not use $, { or }.");
public static void main(String[] args) throws IOException {
String command = args.length == 1 ? args[0] : "";
try {
switch (command) {
case "create" -> createPatient();
case "status" -> showStatus();
case "card" -> startCardSetup();
case "cards" -> listCards();
case "book" -> bookVisit();
case "show" -> showBookings();
case "cancel" -> cancelBooking();
default -> exitWith("Usage: create, status, card, cards, book, show or cancel");
}
} catch (NurishdException error) {
System.out.println("The API answered " + error.status + " " + error.code
+ " (request " + error.requestId + ").");
System.out.println(HINTS.getOrDefault(error.code, "See the Errors page for this code."));
System.exit(1);
}
}The whole program#
# file: visit.py
import json
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from nurishd import NurishdError, call
STATE_FILE = Path("visit-state.json")
PATIENT_STATE = "ON"
PATIENT_TIMEZONE = "America/Toronto"
HINTS = {
"connection_not_active": "The patient has not approved yet, or the connection ended. Run status.",
"connection_scope_not_granted": "The patient did not allow bookings. Create the patient again with a key that holds booking:write.",
"scope_not_granted": "Your key lacks a scope, or your company has no signed BAA.",
"agreements_not_signed": "The patient has not signed the agreements. Run create again and send them the new link.",
"payment_method_required": "The patient has no saved card. Run card, finish it in a browser, then book again.",
"not_licensed_here": "This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
"service_not_bookable": "This service cannot be booked online. Choose another service.",
"slot_taken": "The time is no longer open. Run book again to find a new one.",
"booking_not_cancelable": "The booking is already canceled, completed or past.",
"validation_error": "A field is wrong. In client_note, do not use $, { or }.",
}
def load_state():
if not STATE_FILE.exists():
sys.exit("There is no saved patient yet. Run create first.")
return json.loads(STATE_FILE.read_text())
def load_booking_id(state):
if "booking_id" not in state:
sys.exit("There is no booking yet. Run book first.")
return state["booking_id"]
def save_state(state):
STATE_FILE.write_text(json.dumps(state, indent=2))
def utc_text(moment):
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
def create_patient():
patient = call(
"POST",
"/care/v1/patient/create/document",
body={
"external_id": "tutorial-patient-1",
"email": "ada.lovelace@example.com",
"first_name": "Ada",
"last_name": "Lovelace",
"date_of_birth": "1990-12-10",
"address": {
"line1": "10 Example Street",
"city": "Toronto",
"state": PATIENT_STATE,
"postal_code": "M5V 2T6",
"country": "CA",
},
},
)
save_state(
{
"patient_id": patient["user"],
"connection_id": patient["connection"]["connection_id"],
}
)
print("Open this link in a browser and approve the connection:")
print(patient["connect_url"])
def show_status():
state = load_state()
path = f"/care/v1/connection/{state['connection_id']}/get/document"
connection = call("GET", path)
print(f"Connection status: {connection['status']}")
if connection["status"] != "active":
print("The patient has not approved yet. Run status again later.")
def start_card_setup():
state = load_state()
path = f"/care/v1/patient/{state['patient_id']}/payment-method/setup/create/document"
setup = call("POST", path)
print(f"Card setup {setup['id']} started. Its status is {setup['status']}.")
print("Finish it in a browser, as the Saving a card guide shows.")
def list_cards():
state = load_state()
path = f"/care/v1/patient/{state['patient_id']}/payment-method/query/documents"
cards = call("GET", path)
if not cards["data"]:
print("No card is saved yet.")
for item in cards["data"]:
card = item["card"]
mark = " (default)" if item["is_default"] else ""
print(f"{card['brand']} ending {card['last4']}{mark}")
def find_open_time():
"""Returns the first open time as (specialist_id, service_id, start_time), or None."""
start = datetime.now(timezone.utc)
window = {"from": utc_text(start), "to": utc_text(start + timedelta(days=14))}
people = call(
"GET",
"/care/v1/specialist/query/documents",
params={"type": "Dietitian", "state": PATIENT_STATE, "size": 10},
)
for person in people["data"]:
specialist_id = person["specialist_id"]
path = f"/care/v1/specialist/{specialist_id}/service/query/documents"
for service in call("GET", path)["data"]:
service_id = service["service_id"]
path = (
f"/care/v1/specialist/{specialist_id}/service/{service_id}"
"/availability/query/documents"
)
try:
times = call("GET", path, params=window)
except NurishdError as error:
if error.code == "service_not_bookable":
continue
raise
if times.get("slots"):
return specialist_id, service_id, times["slots"][0]["start_time"]
return None
def book_visit():
state = load_state()
found = find_open_time()
if found is None:
print("No open time in the next 14 days.")
return
specialist_id, service_id, start_time = found
booking = call(
"POST",
"/care/v1/booking/create/document",
body={
"user": state["patient_id"],
"specialist_id": specialist_id,
"service_id": service_id,
"start_time": start_time,
"timezone": PATIENT_TIMEZONE,
"client_note": "I would like to talk about meal planning.",
},
)
state["booking_id"] = booking["booking_id"]
save_state(state)
print(f"Booked {booking['booking_name']} ({booking['booking_id']}).")
print(f"It starts at {booking['start_date']} (UTC). Status: {booking['status']}.")
def show_bookings():
state = load_state()
booking_id = load_booking_id(state)
booking = call("GET", f"/care/v1/booking/{booking_id}/get/document")
print(f"{booking['booking_name']}: {booking['status']}, starts {booking['start_date']}")
answer = call(
"GET",
"/care/v1/booking/query/documents",
params={"patient": state["patient_id"]},
)
print(f"Visits booked for this patient: {answer['total']}")
for item in answer["data"]:
print(f" {item['booking_id']}: {item['status']}, starts {item['start_date']}")
def cancel_booking():
booking_id = load_booking_id(load_state())
booking = call(
"PUT",
f"/care/v1/booking/{booking_id}/cancel/document",
body={"reason": "The patient asked to cancel."},
)
print(f"Booking {booking['booking_id']} is now {booking['status']}.")
COMMANDS = {
"create": create_patient,
"status": show_status,
"card": start_card_setup,
"cards": list_cards,
"book": book_visit,
"show": show_bookings,
"cancel": cancel_booking,
}
def main():
if len(sys.argv) != 2 or sys.argv[1] not in COMMANDS:
print("Usage: python visit.py " + "|".join(COMMANDS))
sys.exit(1)
try:
COMMANDS[sys.argv[1]]()
except NurishdError as error:
print(f"The API answered {error.status} {error.code} (request {error.request_id}).")
print(HINTS.get(error.code, "See the Errors page for this code."))
sys.exit(1)
main()// file: visit.js
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { NurishdError, call } from './nurishd.js';
const STATE_FILE = 'visit-state.json';
const PATIENT_STATE = 'ON';
const PATIENT_TIMEZONE = 'America/Toronto';
const HINTS = {
connection_not_active:
'The patient has not approved yet, or the connection ended. Run status.',
connection_scope_not_granted:
'The patient did not allow bookings. Create the patient again with a key that holds booking:write.',
scope_not_granted:
'Your key lacks a scope, or your company has no signed BAA.',
agreements_not_signed:
'The patient has not signed the agreements. Run create again and send them the new link.',
payment_method_required:
'The patient has no saved card. Run card, finish it in a browser, then book again.',
not_licensed_here:
"This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
service_not_bookable:
'This service cannot be booked online. Choose another service.',
slot_taken: 'The time is no longer open. Run book again to find a new one.',
booking_not_cancelable:
'The booking is already canceled, completed or past.',
validation_error: 'A field is wrong. In client_note, do not use $, { or }.',
};
function exitWith(message) {
console.log(message);
process.exit(1);
}
function loadState() {
if (!existsSync(STATE_FILE)) {
exitWith('There is no saved patient yet. Run create first.');
}
return JSON.parse(readFileSync(STATE_FILE, 'utf8'));
}
function loadBookingId(state) {
if (!state.booking_id) exitWith('There is no booking yet. Run book first.');
return state.booking_id;
}
function saveState(state) {
writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
}
async function createPatient() {
const patient = await call('POST', '/care/v1/patient/create/document', {
body: {
external_id: 'tutorial-patient-1',
email: 'ada.lovelace@example.com',
first_name: 'Ada',
last_name: 'Lovelace',
date_of_birth: '1990-12-10',
address: {
line1: '10 Example Street',
city: 'Toronto',
state: PATIENT_STATE,
postal_code: 'M5V 2T6',
country: 'CA',
},
},
});
saveState({
patient_id: patient.user,
connection_id: patient.connection.connection_id,
});
console.log('Open this link in a browser and approve the connection:');
console.log(patient.connect_url);
}
async function showStatus() {
const state = loadState();
const path = `/care/v1/connection/${state.connection_id}/get/document`;
const connection = await call('GET', path);
console.log(`Connection status: ${connection.status}`);
if (connection.status !== 'active') {
console.log(
'The patient has not approved yet. Run status again later.',
);
}
}
async function startCardSetup() {
const state = loadState();
const path = `/care/v1/patient/${state.patient_id}/payment-method/setup/create/document`;
const setup = await call('POST', path);
console.log(
`Card setup ${setup.id} started. Its status is ${setup.status}.`,
);
console.log('Finish it in a browser, as the Saving a card guide shows.');
}
async function listCards() {
const state = loadState();
const path = `/care/v1/patient/${state.patient_id}/payment-method/query/documents`;
const cards = await call('GET', path);
if (cards.data.length === 0) console.log('No card is saved yet.');
for (const item of cards.data) {
const mark = item.is_default ? ' (default)' : '';
console.log(`${item.card.brand} ending ${item.card.last4}${mark}`);
}
}
/** Returns the first open time as { specialistId, serviceId, startTime }, or null. */
async function findOpenTime() {
const start = new Date();
const end = new Date(start.getTime() + 14 * 24 * 60 * 60 * 1000);
const window = { from: start.toISOString(), to: end.toISOString() };
const people = await call('GET', '/care/v1/specialist/query/documents', {
params: { type: 'Dietitian', state: PATIENT_STATE, size: 10 },
});
for (const person of people.data) {
const specialistId = person.specialist_id;
const path = `/care/v1/specialist/${specialistId}/service/query/documents`;
const services = await call('GET', path);
for (const service of services.data) {
const serviceId = service.service_id;
const timesPath =
`/care/v1/specialist/${specialistId}/service/${serviceId}` +
'/availability/query/documents';
let times;
try {
times = await call('GET', timesPath, { params: window });
} catch (error) {
if (
error instanceof NurishdError &&
error.code === 'service_not_bookable'
) {
continue;
}
throw error;
}
if (times.slots && times.slots.length > 0) {
return {
specialistId,
serviceId,
startTime: times.slots[0].start_time,
};
}
}
}
return null;
}
async function bookVisit() {
const state = loadState();
const found = await findOpenTime();
if (found === null) {
console.log('No open time in the next 14 days.');
return;
}
const booking = await call('POST', '/care/v1/booking/create/document', {
body: {
user: state.patient_id,
specialist_id: found.specialistId,
service_id: found.serviceId,
start_time: found.startTime,
timezone: PATIENT_TIMEZONE,
client_note: 'I would like to talk about meal planning.',
},
});
state.booking_id = booking.booking_id;
saveState(state);
console.log(`Booked ${booking.booking_name} (${booking.booking_id}).`);
console.log(
`It starts at ${booking.start_date} (UTC). Status: ${booking.status}.`,
);
}
async function showBookings() {
const state = loadState();
const bookingId = loadBookingId(state);
const booking = await call(
'GET',
`/care/v1/booking/${bookingId}/get/document`,
);
console.log(
`${booking.booking_name}: ${booking.status}, starts ${booking.start_date}`,
);
const answer = await call('GET', '/care/v1/booking/query/documents', {
params: { patient: state.patient_id },
});
console.log(`Visits booked for this patient: ${answer.total}`);
for (const item of answer.data) {
console.log(
` ${item.booking_id}: ${item.status}, starts ${item.start_date}`,
);
}
}
async function cancelBooking() {
const bookingId = loadBookingId(loadState());
const booking = await call(
'PUT',
`/care/v1/booking/${bookingId}/cancel/document`,
{ body: { reason: 'The patient asked to cancel.' } },
);
console.log(`Booking ${booking.booking_id} is now ${booking.status}.`);
}
const COMMANDS = {
create: createPatient,
status: showStatus,
card: startCardSetup,
cards: listCards,
book: bookVisit,
show: showBookings,
cancel: cancelBooking,
};
async function main() {
const command = COMMANDS[process.argv[2]];
if (!command) {
exitWith(`Usage: node visit.js ${Object.keys(COMMANDS).join('|')}`);
}
try {
await command();
} catch (error) {
if (!(error instanceof NurishdError)) throw error;
console.log(
`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
);
console.log(HINTS[error.code] ?? 'See the Errors page for this code.');
process.exit(1);
}
}
await main();// file: visit.ts
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { NurishdError, call } from './nurishd.ts';
import type { Page } from './nurishd.ts';
interface State {
patient_id: string;
connection_id: string;
booking_id?: string;
}
interface Patient {
user: string;
connection: { connection_id: string };
connect_url: string;
}
interface Booking {
booking_id: string;
booking_name: string;
start_date: string;
status: string;
}
interface Times {
slots?: { start_time: string }[];
}
interface OpenTime {
specialistId: string;
serviceId: string;
startTime: string;
}
const STATE_FILE = 'visit-state.json';
const PATIENT_STATE = 'ON';
const PATIENT_TIMEZONE = 'America/Toronto';
const HINTS: Record<string, string> = {
connection_not_active:
'The patient has not approved yet, or the connection ended. Run status.',
connection_scope_not_granted:
'The patient did not allow bookings. Create the patient again with a key that holds booking:write.',
scope_not_granted:
'Your key lacks a scope, or your company has no signed BAA.',
agreements_not_signed:
'The patient has not signed the agreements. Run create again and send them the new link.',
payment_method_required:
'The patient has no saved card. Run card, finish it in a browser, then book again.',
not_licensed_here:
"This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
service_not_bookable:
'This service cannot be booked online. Choose another service.',
slot_taken: 'The time is no longer open. Run book again to find a new one.',
booking_not_cancelable:
'The booking is already canceled, completed or past.',
validation_error: 'A field is wrong. In client_note, do not use $, { or }.',
};
function exitWith(message: string): never {
console.log(message);
process.exit(1);
}
function loadState(): State {
if (!existsSync(STATE_FILE)) {
exitWith('There is no saved patient yet. Run create first.');
}
return JSON.parse(readFileSync(STATE_FILE, 'utf8'));
}
function loadBookingId(state: State): string {
if (!state.booking_id) exitWith('There is no booking yet. Run book first.');
return state.booking_id;
}
function saveState(state: State) {
writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
}
async function createPatient() {
const patient = await call<Patient>(
'POST',
'/care/v1/patient/create/document',
{
body: {
external_id: 'tutorial-patient-1',
email: 'ada.lovelace@example.com',
first_name: 'Ada',
last_name: 'Lovelace',
date_of_birth: '1990-12-10',
address: {
line1: '10 Example Street',
city: 'Toronto',
state: PATIENT_STATE,
postal_code: 'M5V 2T6',
country: 'CA',
},
},
},
);
saveState({
patient_id: patient.user,
connection_id: patient.connection.connection_id,
});
console.log('Open this link in a browser and approve the connection:');
console.log(patient.connect_url);
}
async function showStatus() {
const state = loadState();
const path = `/care/v1/connection/${state.connection_id}/get/document`;
const connection = await call<{ status: string }>('GET', path);
console.log(`Connection status: ${connection.status}`);
if (connection.status !== 'active') {
console.log(
'The patient has not approved yet. Run status again later.',
);
}
}
async function startCardSetup() {
const state = loadState();
const path = `/care/v1/patient/${state.patient_id}/payment-method/setup/create/document`;
const setup = await call<{ id: string; status: string }>('POST', path);
console.log(
`Card setup ${setup.id} started. Its status is ${setup.status}.`,
);
console.log('Finish it in a browser, as the Saving a card guide shows.');
}
async function listCards() {
const state = loadState();
const path = `/care/v1/patient/${state.patient_id}/payment-method/query/documents`;
const cards = await call<
Page<{
card: { brand: string; last4: string };
is_default: boolean;
}>
>('GET', path);
if (cards.data.length === 0) console.log('No card is saved yet.');
for (const item of cards.data) {
const mark = item.is_default ? ' (default)' : '';
console.log(`${item.card.brand} ending ${item.card.last4}${mark}`);
}
}
/** Returns the first open time as { specialistId, serviceId, startTime }, or null. */
async function findOpenTime(): Promise<OpenTime | null> {
const start = new Date();
const end = new Date(start.getTime() + 14 * 24 * 60 * 60 * 1000);
const window = { from: start.toISOString(), to: end.toISOString() };
const people = await call<Page<{ specialist_id: string }>>(
'GET',
'/care/v1/specialist/query/documents',
{ params: { type: 'Dietitian', state: PATIENT_STATE, size: 10 } },
);
for (const person of people.data) {
const specialistId = person.specialist_id;
const path = `/care/v1/specialist/${specialistId}/service/query/documents`;
const services = await call<Page<{ service_id: string }>>('GET', path);
for (const service of services.data) {
const serviceId = service.service_id;
const timesPath =
`/care/v1/specialist/${specialistId}/service/${serviceId}` +
'/availability/query/documents';
let times: Times;
try {
times = await call<Times>('GET', timesPath, { params: window });
} catch (error) {
if (
error instanceof NurishdError &&
error.code === 'service_not_bookable'
) {
continue;
}
throw error;
}
if (times.slots && times.slots.length > 0) {
return {
specialistId,
serviceId,
startTime: times.slots[0].start_time,
};
}
}
}
return null;
}
async function bookVisit() {
const state = loadState();
const found = await findOpenTime();
if (found === null) {
console.log('No open time in the next 14 days.');
return;
}
const booking = await call<Booking>(
'POST',
'/care/v1/booking/create/document',
{
body: {
user: state.patient_id,
specialist_id: found.specialistId,
service_id: found.serviceId,
start_time: found.startTime,
timezone: PATIENT_TIMEZONE,
client_note: 'I would like to talk about meal planning.',
},
},
);
state.booking_id = booking.booking_id;
saveState(state);
console.log(`Booked ${booking.booking_name} (${booking.booking_id}).`);
console.log(
`It starts at ${booking.start_date} (UTC). Status: ${booking.status}.`,
);
}
async function showBookings() {
const state = loadState();
const bookingId = loadBookingId(state);
const booking = await call<Booking>(
'GET',
`/care/v1/booking/${bookingId}/get/document`,
);
console.log(
`${booking.booking_name}: ${booking.status}, starts ${booking.start_date}`,
);
const answer = await call<Page<Booking>>(
'GET',
'/care/v1/booking/query/documents',
{ params: { patient: state.patient_id } },
);
console.log(`Visits booked for this patient: ${answer.total}`);
for (const item of answer.data) {
console.log(
` ${item.booking_id}: ${item.status}, starts ${item.start_date}`,
);
}
}
async function cancelBooking() {
const bookingId = loadBookingId(loadState());
const booking = await call<Booking>(
'PUT',
`/care/v1/booking/${bookingId}/cancel/document`,
{ body: { reason: 'The patient asked to cancel.' } },
);
console.log(`Booking ${booking.booking_id} is now ${booking.status}.`);
}
const COMMANDS = {
create: createPatient,
status: showStatus,
card: startCardSetup,
cards: listCards,
book: bookVisit,
show: showBookings,
cancel: cancelBooking,
};
async function main() {
const command = COMMANDS[process.argv[2] as keyof typeof COMMANDS];
if (!command) {
exitWith(`Usage: node visit.js ${Object.keys(COMMANDS).join('|')}`);
}
try {
await command();
} catch (error) {
if (!(error instanceof NurishdError)) throw error;
console.log(
`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
);
console.log(HINTS[error.code] ?? 'See the Errors page for this code.');
process.exit(1);
}
}
await main();// file: src/main/java/tutorial/Visit.java
package tutorial;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import tutorial.Nurishd.NurishdException;
public class Visit {
static final Path STATE_FILE = Path.of("visit-state.json");
static final String PATIENT_STATE = "ON";
static final String PATIENT_TIMEZONE = "America/Toronto";
static final Map<String, String> HINTS = Map.of(
"connection_not_active",
"The patient has not approved yet, or the connection ended. Run status.",
"connection_scope_not_granted",
"The patient did not allow bookings. Create the patient again with a key that holds booking:write.",
"scope_not_granted",
"Your key lacks a scope, or your company has no signed BAA.",
"agreements_not_signed",
"The patient has not signed the agreements. Run create again and send them the new link.",
"payment_method_required",
"The patient has no saved card. Run card, finish it in a browser, then book again.",
"not_licensed_here",
"This dietitian cannot serve this booking. Choose another dietitian and check the patient's address.",
"service_not_bookable",
"This service cannot be booked online. Choose another service.",
"slot_taken",
"The time is no longer open. Run book again to find a new one.",
"booking_not_cancelable",
"The booking is already canceled, completed or past.",
"validation_error",
"A field is wrong. In client_note, do not use $, { or }.");
static void exitWith(String message) {
System.out.println(message);
System.exit(1);
}
static ObjectNode loadState() throws IOException {
if (!Files.exists(STATE_FILE)) {
exitWith("There is no saved patient yet. Run create first.");
}
return (ObjectNode) Nurishd.JSON.readTree(Files.readString(STATE_FILE));
}
static String loadBookingId(ObjectNode state) {
if (!state.has("booking_id")) {
exitWith("There is no booking yet. Run book first.");
}
return state.get("booking_id").asText();
}
static void saveState(ObjectNode state) throws IOException {
Files.writeString(STATE_FILE, Nurishd.JSON.writerWithDefaultPrettyPrinter().writeValueAsString(state));
}
static void createPatient() throws IOException {
Map<String, Object> address = Map.of(
"line1", "10 Example Street",
"city", "Toronto",
"state", PATIENT_STATE,
"postal_code", "M5V 2T6",
"country", "CA");
Map<String, Object> body = Map.of(
"external_id", "tutorial-patient-1",
"email", "ada.lovelace@example.com",
"first_name", "Ada",
"last_name", "Lovelace",
"date_of_birth", "1990-12-10",
"address", address);
JsonNode patient = Nurishd.call("POST", "/care/v1/patient/create/document", Map.of(), body);
ObjectNode state = Nurishd.JSON.createObjectNode();
state.put("patient_id", patient.path("user").asText());
state.put("connection_id", patient.path("connection").path("connection_id").asText());
saveState(state);
System.out.println("Open this link in a browser and approve the connection:");
System.out.println(patient.path("connect_url").asText());
}
static void showStatus() throws IOException {
ObjectNode state = loadState();
String path = "/care/v1/connection/%s/get/document".formatted(state.get("connection_id").asText());
JsonNode connection = Nurishd.call("GET", path);
System.out.println("Connection status: " + connection.path("status").asText());
if (!connection.path("status").asText().equals("active")) {
System.out.println("The patient has not approved yet. Run status again later.");
}
}
static void startCardSetup() throws IOException {
ObjectNode state = loadState();
String path = "/care/v1/patient/%s/payment-method/setup/create/document"
.formatted(state.get("patient_id").asText());
JsonNode setup = Nurishd.call("POST", path);
System.out.println("Card setup " + setup.path("id").asText() + " started. Its status is "
+ setup.path("status").asText() + ".");
System.out.println("Finish it in a browser, as the Saving a card guide shows.");
}
static void listCards() throws IOException {
ObjectNode state = loadState();
String path = "/care/v1/patient/%s/payment-method/query/documents"
.formatted(state.get("patient_id").asText());
JsonNode cards = Nurishd.call("GET", path);
if (cards.path("data").isEmpty()) {
System.out.println("No card is saved yet.");
}
for (JsonNode item : cards.path("data")) {
String mark = item.path("is_default").asBoolean() ? " (default)" : "";
System.out.println(item.path("card").path("brand").asText() + " ending "
+ item.path("card").path("last4").asText() + mark);
}
}
/** Returns the first open time as {specialistId, serviceId, startTime}, or null. */
static String[] findOpenTime() {
Instant start = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Map<String, Object> window =
Map.of("from", start.toString(), "to", start.plus(14, ChronoUnit.DAYS).toString());
JsonNode people = Nurishd.call(
"GET",
"/care/v1/specialist/query/documents",
Map.of("type", "Dietitian", "state", PATIENT_STATE, "size", 10),
null);
for (JsonNode person : people.path("data")) {
String specialistId = person.path("specialist_id").asText();
String path = "/care/v1/specialist/%s/service/query/documents".formatted(specialistId);
for (JsonNode service : Nurishd.call("GET", path).path("data")) {
String serviceId = service.path("service_id").asText();
String timesPath = "/care/v1/specialist/%s/service/%s/availability/query/documents"
.formatted(specialistId, serviceId);
JsonNode times;
try {
times = Nurishd.call("GET", timesPath, window, null);
} catch (NurishdException error) {
if (error.code.equals("service_not_bookable")) {
continue;
}
throw error;
}
if (!times.path("slots").isEmpty()) {
String startTime = times.path("slots").get(0).path("start_time").asText();
return new String[] {specialistId, serviceId, startTime};
}
}
}
return null;
}
static void bookVisit() throws IOException {
ObjectNode state = loadState();
String[] found = findOpenTime();
if (found == null) {
System.out.println("No open time in the next 14 days.");
return;
}
Map<String, Object> body = Map.of(
"user", state.get("patient_id").asText(),
"specialist_id", found[0],
"service_id", found[1],
"start_time", found[2],
"timezone", PATIENT_TIMEZONE,
"client_note", "I would like to talk about meal planning.");
JsonNode booking = Nurishd.call("POST", "/care/v1/booking/create/document", Map.of(), body);
state.put("booking_id", booking.path("booking_id").asText());
saveState(state);
System.out.println("Booked " + booking.path("booking_name").asText() + " ("
+ booking.path("booking_id").asText() + ").");
System.out.println("It starts at " + booking.path("start_date").asText()
+ " (UTC). Status: " + booking.path("status").asText() + ".");
}
static void showBookings() throws IOException {
ObjectNode state = loadState();
String bookingId = loadBookingId(state);
JsonNode booking = Nurishd.call("GET", "/care/v1/booking/%s/get/document".formatted(bookingId));
System.out.println(booking.path("booking_name").asText() + ": " + booking.path("status").asText()
+ ", starts " + booking.path("start_date").asText());
JsonNode answer = Nurishd.call(
"GET",
"/care/v1/booking/query/documents",
Map.of("patient", state.get("patient_id").asText()),
null);
System.out.println("Visits booked for this patient: " + answer.path("total").asInt());
for (JsonNode item : answer.path("data")) {
System.out.println(" " + item.path("booking_id").asText() + ": "
+ item.path("status").asText() + ", starts " + item.path("start_date").asText());
}
}
static void cancelBooking() throws IOException {
String bookingId = loadBookingId(loadState());
JsonNode booking = Nurishd.call(
"PUT",
"/care/v1/booking/%s/cancel/document".formatted(bookingId),
Map.of(),
Map.of("reason", "The patient asked to cancel."));
System.out.println("Booking " + booking.path("booking_id").asText() + " is now "
+ booking.path("status").asText() + ".");
}
public static void main(String[] args) throws IOException {
String command = args.length == 1 ? args[0] : "";
try {
switch (command) {
case "create" -> createPatient();
case "status" -> showStatus();
case "card" -> startCardSetup();
case "cards" -> listCards();
case "book" -> bookVisit();
case "show" -> showBookings();
case "cancel" -> cancelBooking();
default -> exitWith("Usage: create, status, card, cards, book, show or cancel");
}
} catch (NurishdException error) {
System.out.println("The API answered " + error.status + " " + error.code
+ " (request " + error.requestId + ").");
System.out.println(HINTS.getOrDefault(error.code, "See the Errors page for this code."));
System.exit(1);
}
}
}If something goes wrong#
| What you see | Why | What to do |
|---|---|---|
403 scope_not_granted | The key lacks a scope, or your company has no signed BAA. | Use a key with the four scopes. Ask Nurish'd about the BAA. See BAA handling. |
403 connection_scope_not_granted | The patient did not allow bookings. | Create the patient again with a key that holds booking:write. Send the new link. |
409 connection_not_active | The patient has not approved, declined, or the connection was revoked. | Run status. Wait for approval, or run create again for a new link. |
409 agreements_not_signed | The patient has not signed the agreements a visit needs. | Run create again and send the patient to the new link. |
409 payment_method_required | The patient has no saved card. | Do step 4, then book again. |
409 not_licensed_here | The dietitian cannot serve this booking yet. | Offer another dietitian. Check that the patient has an address. |
409 slot_taken | The time is no longer open. | Read the open times again and book another. |
409 service_not_bookable | The service cannot be booked online, or the dietitian or service is unknown. | Offer another service. |
409 booking_not_cancelable | The booking is already canceled, completed or past. | Run show to read its status. |
409 external_id_conflict | The external_id already belongs to a patient with a different email. | Keep the first email for this id. |
422 validation_error | A field is wrong, for example a client_note with $, { or }. | Fix the field. Do not send the same request again. |
404 not_found | The patient or booking does not exist, or belongs to another company. | Check the ids in visit-state.json. |
Next#
- Connecting a patient: statuses, revoking a connection and return URLs.
- Saving a card: the browser part of step 4.
- Booking a visit: every filter and field.
- Show dietitians and their open times: display the choices to a patient.
- Read visit reports: read the report after a visit.
Something wrong on this page? Email hello@nurishd.io with the page address.