Show dietitians and their open times
Write a command-line program that lists the dietitians a patient can book, what each one offers, and the open times of one service.
You build a command-line program with three commands. One lists the dietitians in a province with their services and prices. One prints a dietitian's profile. One prints the open times of a service for the next days, grouped by day in the patient's time zone.
The API calls a dietitian a specialist. It calls an appointment a booking, and this page also says visit. The code uses the API's words. The text says dietitian where it helps.
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 scope
specialist:read. This scope needs no patient and no BAA. Run the key check from the setup tutorial to see your scopes. - Python only: Windows has no time zone data, so run
pip install tzdata. Other systems already have it.
In the Sandbox the calendars are simulated: open times are generated for weekdays from 9 to 5. They are not real calendars. See Environments.
1. Choose the inputs#
The program needs two facts about the patient.
- Province. A dietitian must be licensed where the patient lives. You pass it as two capital letters, such as
ON. The list then shows only dietitians who practise there. - Time zone. A name from the IANA list, such as
America/Toronto.
You will type them as command arguments. In a real app they come from the patient's address.
2. List the dietitians and their services#
GET /care/v1/specialist/query/documents returns a page of specialists. The filter type=Dietitian keeps dietitians only. The filter state keeps the ones who practise in that province. The program asks for 10. If you need more, read Pagination.
A service is one kind of visit a dietitian offers, for example an initial consult. GET /care/v1/specialist/{specialist_id}/service/query/documents lists them. Each service has a length in minutes and a price in cents. 15000 cents is 150.00 CAD. The program divides by 100 only to print. Never do money math with decimals. Keep cents.
import sys
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from nurishd import NurishdError, call
def money(cents, currency):
return f"{cents / 100:.2f} {currency}"
def list_services(specialist_id):
path = f"/care/v1/specialist/{specialist_id}/service/query/documents"
answer = call("GET", path)
if not answer["data"]:
print(" no services")
for service in answer["data"]:
price = money(service["service_price_in_cents"], service["service_currency"])
print(f" service: {service['service_name']} ({service['service_id']})")
print(
f" {service['service_duration_in_minutes']} minutes, {price}, "
f"{service['service_mode_of_delivery']}"
)
def list_dietitians(state):
answer = call(
"GET",
"/care/v1/specialist/query/documents",
params={"type": "Dietitian", "state": state, "size": 10},
)
for person in answer["data"]:
focus = ", ".join(person.get("specialist_specializations", []))
print(f"{person['specialist_first_name']} {person['specialist_last_name']}")
print(f" id: {person['specialist_id']}")
print(f" focus: {focus}")
list_services(person["specialist_id"])import { NurishdError, call } from './nurishd.js';
function money(cents, currency) {
return `${(cents / 100).toFixed(2)} ${currency}`;
}
async function listServices(specialistId) {
const path = `/care/v1/specialist/${specialistId}/service/query/documents`;
const answer = await call('GET', path);
if (answer.data.length === 0) console.log(' no services');
for (const service of answer.data) {
const price = money(
service.service_price_in_cents,
service.service_currency,
);
console.log(
` service: ${service.service_name} (${service.service_id})`,
);
console.log(
` ${service.service_duration_in_minutes} minutes, ${price}, ` +
service.service_mode_of_delivery,
);
}
}
async function listDietitians(state) {
const answer = await call('GET', '/care/v1/specialist/query/documents', {
params: { type: 'Dietitian', state, size: 10 },
});
for (const person of answer.data) {
const focus = (person.specialist_specializations ?? []).join(', ');
console.log(
`${person.specialist_first_name} ${person.specialist_last_name}`,
);
console.log(` id: ${person.specialist_id}`);
console.log(` focus: ${focus}`);
await listServices(person.specialist_id);
}
}import { NurishdError, call } from './nurishd.ts';
import type { Page } from './nurishd.ts';
function money(cents: number, currency: string) {
return `${(cents / 100).toFixed(2)} ${currency}`;
}
async function listServices(specialistId: string) {
const path = `/care/v1/specialist/${specialistId}/service/query/documents`;
const answer = await call<Page<Service>>('GET', path);
if (answer.data.length === 0) console.log(' no services');
for (const service of answer.data) {
const price = money(
service.service_price_in_cents,
service.service_currency,
);
console.log(
` service: ${service.service_name} (${service.service_id})`,
);
console.log(
` ${service.service_duration_in_minutes} minutes, ${price}, ` +
service.service_mode_of_delivery,
);
}
}
async function listDietitians(state: string) {
const answer = await call<Page<Specialist>>(
'GET',
'/care/v1/specialist/query/documents',
{ params: { type: 'Dietitian', state, size: 10 } },
);
for (const person of answer.data) {
const focus = (person.specialist_specializations ?? []).join(', ');
console.log(
`${person.specialist_first_name} ${person.specialist_last_name}`,
);
console.log(` id: ${person.specialist_id}`);
console.log(` focus: ${focus}`);
await listServices(person.specialist_id);
}
}package tutorial;
import com.fasterxml.jackson.databind.JsonNode;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import tutorial.Nurishd.NurishdException;
static String money(long cents, String currency) {
return String.format("%.2f %s", cents / 100.0, currency);
}
static void listServices(String specialistId) {
String path = "/care/v1/specialist/%s/service/query/documents".formatted(specialistId);
JsonNode answer = Nurishd.call("GET", path);
if (answer.path("data").isEmpty()) {
System.out.println(" no services");
}
for (JsonNode service : answer.path("data")) {
String price = money(
service.path("service_price_in_cents").asLong(),
service.path("service_currency").asText());
System.out.println(" service: " + service.path("service_name").asText()
+ " (" + service.path("service_id").asText() + ")");
System.out.println(" " + service.path("service_duration_in_minutes").asInt()
+ " minutes, " + price + ", "
+ service.path("service_mode_of_delivery").asText());
}
}
static void listDietitians(String state) {
JsonNode answer = Nurishd.call(
"GET",
"/care/v1/specialist/query/documents",
Map.of("type", "Dietitian", "state", state, "size", 10),
null);
for (JsonNode person : answer.path("data")) {
List<String> focus = new ArrayList<>();
person.path("specialist_specializations").forEach(item -> focus.add(item.asText()));
System.out.println(person.path("specialist_first_name").asText() + " "
+ person.path("specialist_last_name").asText());
System.out.println(" id: " + person.path("specialist_id").asText());
System.out.println(" focus: " + String.join(", ", focus));
listServices(person.path("specialist_id").asText());
}
}Do not pick the first dietitian in the list without looking at the services. A dietitian can have no service that can be booked online. A service delivered In Person cannot be booked through the API. Step 4 shows what happens if you ask.
3. Read one profile#
The list leaves out specialist_long_introduction, the longer text a dietitian writes about themselves. GET /care/v1/specialist/{specialist_id}/get/document returns the full profile. Call it when the patient opens a dietitian.
def show_profile(specialist_id):
person = call("GET", f"/care/v1/specialist/{specialist_id}/get/document")
print(f"{person['specialist_first_name']} {person['specialist_last_name']}")
print(person.get("specialist_long_introduction") or "No introduction.")async function showProfile(specialistId) {
const person = await call(
'GET',
`/care/v1/specialist/${specialistId}/get/document`,
);
console.log(
`${person.specialist_first_name} ${person.specialist_last_name}`,
);
console.log(person.specialist_long_introduction ?? 'No introduction.');
}async function showProfile(specialistId: string) {
const person = await call<Specialist>(
'GET',
`/care/v1/specialist/${specialistId}/get/document`,
);
console.log(
`${person.specialist_first_name} ${person.specialist_last_name}`,
);
console.log(person.specialist_long_introduction ?? 'No introduction.');
}static void showProfile(String specialistId) {
JsonNode person =
Nurishd.call("GET", "/care/v1/specialist/%s/get/document".formatted(specialistId));
System.out.println(person.path("specialist_first_name").asText() + " "
+ person.path("specialist_last_name").asText());
System.out.println(person.path("specialist_long_introduction").asText("No introduction."));
}4. Read the open times#
GET /care/v1/specialist/{specialist_id}/service/{service_id}/availability/query/documents returns the times a patient can still book. It needs two query parameters, from and to. Both carry a UTC offset. The range must be at most 31 days. A from in the past is moved up to the present.
A service that cannot be booked online answers 409 service_not_bookable. The program catches that code and prints a message.
The times come back in UTC. UTC is the world reference time, with no daylight saving. Convert each time to the patient's time zone before you show it. The program does this with the tool each language already has: zoneinfo in Python, Intl.DateTimeFormat in JavaScript and TypeScript, and java.time in Java. It then groups the times by local day. A time late in the evening in Toronto can be the next day in UTC, so group after you convert, never before.
def utc_text(moment):
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
def show_times(specialist_id, service_id, zone_name, days):
zone = ZoneInfo(zone_name)
start = datetime.now(timezone.utc)
path = (
f"/care/v1/specialist/{specialist_id}/service/{service_id}"
"/availability/query/documents"
)
try:
answer = call(
"GET",
path,
params={
"from": utc_text(start),
"to": utc_text(start + timedelta(days=days)),
},
)
except NurishdError as error:
if error.code == "service_not_bookable":
print("This service cannot be booked online. Choose another one.")
return
raise
times_by_day = {}
for slot in answer.get("slots", []):
utc_time = datetime.fromisoformat(slot["start_time"].replace("Z", "+00:00"))
local = utc_time.astimezone(zone)
day = local.strftime("%A %Y-%m-%d")
times_by_day.setdefault(day, []).append(local.strftime("%H:%M"))
if not times_by_day:
print("No open times in this range.")
for day, times in times_by_day.items():
print(f"{day}: {', '.join(times)}")async function showTimes(specialistId, serviceId, zone, days) {
const start = new Date();
const end = new Date(start.getTime() + days * 24 * 60 * 60 * 1000);
const path =
`/care/v1/specialist/${specialistId}/service/${serviceId}` +
'/availability/query/documents';
let answer;
try {
answer = await call('GET', path, {
params: { from: start.toISOString(), to: end.toISOString() },
});
} catch (error) {
if (
error instanceof NurishdError &&
error.code === 'service_not_bookable'
) {
console.log(
'This service cannot be booked online. Choose another one.',
);
return;
}
throw error;
}
const dateFormat = new Intl.DateTimeFormat('en-CA', {
timeZone: zone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
const weekdayFormat = new Intl.DateTimeFormat('en-US', {
timeZone: zone,
weekday: 'long',
});
const timeFormat = new Intl.DateTimeFormat('en-GB', {
timeZone: zone,
hour: '2-digit',
minute: '2-digit',
});
const timesByDay = new Map();
for (const slot of answer.slots ?? []) {
const moment = new Date(slot.start_time);
const day = `${weekdayFormat.format(moment)} ${dateFormat.format(moment)}`;
if (!timesByDay.has(day)) timesByDay.set(day, []);
timesByDay.get(day).push(timeFormat.format(moment));
}
if (timesByDay.size === 0) console.log('No open times in this range.');
for (const [day, times] of timesByDay) {
console.log(`${day}: ${times.join(', ')}`);
}
}async function showTimes(
specialistId: string,
serviceId: string,
zone: string,
days: number,
) {
const start = new Date();
const end = new Date(start.getTime() + days * 24 * 60 * 60 * 1000);
const path =
`/care/v1/specialist/${specialistId}/service/${serviceId}` +
'/availability/query/documents';
let answer: Availability;
try {
answer = await call<Availability>('GET', path, {
params: { from: start.toISOString(), to: end.toISOString() },
});
} catch (error) {
if (
error instanceof NurishdError &&
error.code === 'service_not_bookable'
) {
console.log(
'This service cannot be booked online. Choose another one.',
);
return;
}
throw error;
}
const dateFormat = new Intl.DateTimeFormat('en-CA', {
timeZone: zone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
const weekdayFormat = new Intl.DateTimeFormat('en-US', {
timeZone: zone,
weekday: 'long',
});
const timeFormat = new Intl.DateTimeFormat('en-GB', {
timeZone: zone,
hour: '2-digit',
minute: '2-digit',
});
const timesByDay = new Map<string, string[]>();
for (const slot of answer.slots ?? []) {
const moment = new Date(slot.start_time);
const day = `${weekdayFormat.format(moment)} ${dateFormat.format(moment)}`;
if (!timesByDay.has(day)) timesByDay.set(day, []);
timesByDay.get(day)?.push(timeFormat.format(moment));
}
if (timesByDay.size === 0) console.log('No open times in this range.');
for (const [day, times] of timesByDay) {
console.log(`${day}: ${times.join(', ')}`);
}
}static void showTimes(String specialistId, String serviceId, String zoneName, int days) {
ZoneId zone = ZoneId.of(zoneName);
Instant start = Instant.now().truncatedTo(ChronoUnit.SECONDS);
String path = "/care/v1/specialist/%s/service/%s/availability/query/documents"
.formatted(specialistId, serviceId);
JsonNode answer;
try {
answer = Nurishd.call(
"GET",
path,
Map.of("from", start.toString(), "to", start.plus(days, ChronoUnit.DAYS).toString()),
null);
} catch (NurishdException error) {
if (error.code.equals("service_not_bookable")) {
System.out.println("This service cannot be booked online. Choose another one.");
return;
}
throw error;
}
DateTimeFormatter dayFormat = DateTimeFormatter.ofPattern("EEEE yyyy-MM-dd", Locale.US);
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm");
Map<String, List<String>> timesByDay = new LinkedHashMap<>();
for (JsonNode slot : answer.path("slots")) {
ZonedDateTime local =
OffsetDateTime.parse(slot.path("start_time").asText()).atZoneSameInstant(zone);
timesByDay
.computeIfAbsent(dayFormat.format(local), day -> new ArrayList<>())
.add(timeFormat.format(local));
}
if (timesByDay.isEmpty()) {
System.out.println("No open times in this range.");
}
timesByDay.forEach((day, times) -> System.out.println(day + ": " + String.join(", ", times)));
}5. Choose the command#
The last function reads the command line and runs one of the three commands. It also catches an error answer and prints its status and code. It prints the request_id too. Send that id to support if you need help.
def main():
args = sys.argv[1:]
try:
if len(args) == 2 and args[0] == "list":
list_dietitians(args[1])
elif len(args) == 2 and args[0] == "profile":
show_profile(args[1])
elif len(args) in (4, 5) and args[0] == "times":
days = int(args[4]) if len(args) == 5 else 7
show_times(args[1], args[2], args[3], days)
else:
print("Usage:")
print(" python dietitians.py list ON")
print(" python dietitians.py profile SPECIALIST_ID")
print(" python dietitians.py times SPECIALIST_ID SERVICE_ID America/Toronto [DAYS]")
except NurishdError as error:
print(f"The API answered {error.status} {error.code} (request {error.request_id}).")
sys.exit(1)async function main() {
const args = process.argv.slice(2);
try {
if (args.length === 2 && args[0] === 'list') {
await listDietitians(args[1]);
} else if (args.length === 2 && args[0] === 'profile') {
await showProfile(args[1]);
} else if (
(args.length === 4 || args.length === 5) &&
args[0] === 'times'
) {
const days = args.length === 5 ? Number(args[4]) : 7;
await showTimes(args[1], args[2], args[3], days);
} else {
console.log('Usage:');
console.log(' node dietitians.js list ON');
console.log(' node dietitians.js profile SPECIALIST_ID');
console.log(
' node dietitians.js times SPECIALIST_ID SERVICE_ID America/Toronto [DAYS]',
);
}
} catch (error) {
if (!(error instanceof NurishdError)) throw error;
console.log(
`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
);
process.exit(1);
}
}async function main() {
const args = process.argv.slice(2);
try {
if (args.length === 2 && args[0] === 'list') {
await listDietitians(args[1]);
} else if (args.length === 2 && args[0] === 'profile') {
await showProfile(args[1]);
} else if (
(args.length === 4 || args.length === 5) &&
args[0] === 'times'
) {
const days = args.length === 5 ? Number(args[4]) : 7;
await showTimes(args[1], args[2], args[3], days);
} else {
console.log('Usage:');
console.log(' node dietitians.js list ON');
console.log(' node dietitians.js profile SPECIALIST_ID');
console.log(
' node dietitians.js times SPECIALIST_ID SERVICE_ID America/Toronto [DAYS]',
);
}
} catch (error) {
if (!(error instanceof NurishdError)) throw error;
console.log(
`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
);
process.exit(1);
}
}public static void main(String[] args) {
try {
if (args.length == 2 && args[0].equals("list")) {
listDietitians(args[1]);
} else if (args.length == 2 && args[0].equals("profile")) {
showProfile(args[1]);
} else if ((args.length == 4 || args.length == 5) && args[0].equals("times")) {
int days = args.length == 5 ? Integer.parseInt(args[4]) : 7;
showTimes(args[1], args[2], args[3], days);
} else {
System.out.println("Usage:");
System.out.println(" list ON");
System.out.println(" profile SPECIALIST_ID");
System.out.println(" times SPECIALIST_ID SERVICE_ID America/Toronto [DAYS]");
}
} catch (NurishdException error) {
System.out.println("The API answered " + error.status + " " + error.code
+ " (request " + error.requestId + ").");
System.exit(1);
}
}6. Run it#
List the dietitians in Toronto.
- Python:
python dietitians.py list ON - JavaScript:
node dietitians.js list ON - TypeScript:
node dietitians.ts list ON - Java:
mvn -q compile exec:java -Dexec.mainClass=tutorial.Dietitians -Dexec.args="list ON"
You see each dietitian with an id, a focus and the services:
Maya Okafor
id: 3b7d9a52-0000-4000-8000-0000000000a1
focus: Weight Loss/Management
service: Initial consult (service-initial-consult)
60 minutes, 150.00 CAD, Virtual
service: Follow-up (service-follow-up)
30 minutes, 80.00 CAD, Virtual
Daniel Reyes
id: 3b7d9a52-0000-4000-8000-0000000000a2
focus: Sports Nutrition
service: Intro visit (service-intro)
45 minutes, 120.00 CAD, Virtual
service: Clinic visit (service-clinic)
60 minutes, 150.00 CAD, In Person
Priya Nair
id: 3b7d9a52-0000-4000-8000-0000000000a3
focus: Diabetes
service: Clinic visit (service-clinic)
60 minutes, 150.00 CAD, In PersonCopy a specialist_id and a service_id from the output. Ask for the open times of the next 2 days in the patient's time zone. The commands below show Python. The other languages take the same arguments after the program name.
python dietitians.py times 3b7d9a52-0000-4000-8000-0000000000a1 service-initial-consult America/Toronto 2You see the days and the local times:
Thursday 2026-11-19: 14:00, 15:00, 16:00
Friday 2026-11-20: 09:00, 10:00, 11:00, 12:00, 13:00, 14:00, 15:00, 16:00The first day starts later than 09:00 because the program asks from now on. The date and the times you see depend on the day you run it.
Ask for a service delivered in person:
python dietitians.py times 3b7d9a52-0000-4000-8000-0000000000a2 service-clinic America/TorontoThis service cannot be booked online. Choose another one.The whole program#
# file: dietitians.py
import sys
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from nurishd import NurishdError, call
def money(cents, currency):
return f"{cents / 100:.2f} {currency}"
def utc_text(moment):
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
def list_services(specialist_id):
path = f"/care/v1/specialist/{specialist_id}/service/query/documents"
answer = call("GET", path)
if not answer["data"]:
print(" no services")
for service in answer["data"]:
price = money(service["service_price_in_cents"], service["service_currency"])
print(f" service: {service['service_name']} ({service['service_id']})")
print(
f" {service['service_duration_in_minutes']} minutes, {price}, "
f"{service['service_mode_of_delivery']}"
)
def list_dietitians(state):
answer = call(
"GET",
"/care/v1/specialist/query/documents",
params={"type": "Dietitian", "state": state, "size": 10},
)
for person in answer["data"]:
focus = ", ".join(person.get("specialist_specializations", []))
print(f"{person['specialist_first_name']} {person['specialist_last_name']}")
print(f" id: {person['specialist_id']}")
print(f" focus: {focus}")
list_services(person["specialist_id"])
def show_profile(specialist_id):
person = call("GET", f"/care/v1/specialist/{specialist_id}/get/document")
print(f"{person['specialist_first_name']} {person['specialist_last_name']}")
print(person.get("specialist_long_introduction") or "No introduction.")
def show_times(specialist_id, service_id, zone_name, days):
zone = ZoneInfo(zone_name)
start = datetime.now(timezone.utc)
path = (
f"/care/v1/specialist/{specialist_id}/service/{service_id}"
"/availability/query/documents"
)
try:
answer = call(
"GET",
path,
params={
"from": utc_text(start),
"to": utc_text(start + timedelta(days=days)),
},
)
except NurishdError as error:
if error.code == "service_not_bookable":
print("This service cannot be booked online. Choose another one.")
return
raise
times_by_day = {}
for slot in answer.get("slots", []):
utc_time = datetime.fromisoformat(slot["start_time"].replace("Z", "+00:00"))
local = utc_time.astimezone(zone)
day = local.strftime("%A %Y-%m-%d")
times_by_day.setdefault(day, []).append(local.strftime("%H:%M"))
if not times_by_day:
print("No open times in this range.")
for day, times in times_by_day.items():
print(f"{day}: {', '.join(times)}")
def main():
args = sys.argv[1:]
try:
if len(args) == 2 and args[0] == "list":
list_dietitians(args[1])
elif len(args) == 2 and args[0] == "profile":
show_profile(args[1])
elif len(args) in (4, 5) and args[0] == "times":
days = int(args[4]) if len(args) == 5 else 7
show_times(args[1], args[2], args[3], days)
else:
print("Usage:")
print(" python dietitians.py list ON")
print(" python dietitians.py profile SPECIALIST_ID")
print(" python dietitians.py times SPECIALIST_ID SERVICE_ID America/Toronto [DAYS]")
except NurishdError as error:
print(f"The API answered {error.status} {error.code} (request {error.request_id}).")
sys.exit(1)
main()// file: dietitians.js
import { NurishdError, call } from './nurishd.js';
function money(cents, currency) {
return `${(cents / 100).toFixed(2)} ${currency}`;
}
async function listServices(specialistId) {
const path = `/care/v1/specialist/${specialistId}/service/query/documents`;
const answer = await call('GET', path);
if (answer.data.length === 0) console.log(' no services');
for (const service of answer.data) {
const price = money(
service.service_price_in_cents,
service.service_currency,
);
console.log(
` service: ${service.service_name} (${service.service_id})`,
);
console.log(
` ${service.service_duration_in_minutes} minutes, ${price}, ` +
service.service_mode_of_delivery,
);
}
}
async function listDietitians(state) {
const answer = await call('GET', '/care/v1/specialist/query/documents', {
params: { type: 'Dietitian', state, size: 10 },
});
for (const person of answer.data) {
const focus = (person.specialist_specializations ?? []).join(', ');
console.log(
`${person.specialist_first_name} ${person.specialist_last_name}`,
);
console.log(` id: ${person.specialist_id}`);
console.log(` focus: ${focus}`);
await listServices(person.specialist_id);
}
}
async function showProfile(specialistId) {
const person = await call(
'GET',
`/care/v1/specialist/${specialistId}/get/document`,
);
console.log(
`${person.specialist_first_name} ${person.specialist_last_name}`,
);
console.log(person.specialist_long_introduction ?? 'No introduction.');
}
async function showTimes(specialistId, serviceId, zone, days) {
const start = new Date();
const end = new Date(start.getTime() + days * 24 * 60 * 60 * 1000);
const path =
`/care/v1/specialist/${specialistId}/service/${serviceId}` +
'/availability/query/documents';
let answer;
try {
answer = await call('GET', path, {
params: { from: start.toISOString(), to: end.toISOString() },
});
} catch (error) {
if (
error instanceof NurishdError &&
error.code === 'service_not_bookable'
) {
console.log(
'This service cannot be booked online. Choose another one.',
);
return;
}
throw error;
}
const dateFormat = new Intl.DateTimeFormat('en-CA', {
timeZone: zone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
const weekdayFormat = new Intl.DateTimeFormat('en-US', {
timeZone: zone,
weekday: 'long',
});
const timeFormat = new Intl.DateTimeFormat('en-GB', {
timeZone: zone,
hour: '2-digit',
minute: '2-digit',
});
const timesByDay = new Map();
for (const slot of answer.slots ?? []) {
const moment = new Date(slot.start_time);
const day = `${weekdayFormat.format(moment)} ${dateFormat.format(moment)}`;
if (!timesByDay.has(day)) timesByDay.set(day, []);
timesByDay.get(day).push(timeFormat.format(moment));
}
if (timesByDay.size === 0) console.log('No open times in this range.');
for (const [day, times] of timesByDay) {
console.log(`${day}: ${times.join(', ')}`);
}
}
async function main() {
const args = process.argv.slice(2);
try {
if (args.length === 2 && args[0] === 'list') {
await listDietitians(args[1]);
} else if (args.length === 2 && args[0] === 'profile') {
await showProfile(args[1]);
} else if (
(args.length === 4 || args.length === 5) &&
args[0] === 'times'
) {
const days = args.length === 5 ? Number(args[4]) : 7;
await showTimes(args[1], args[2], args[3], days);
} else {
console.log('Usage:');
console.log(' node dietitians.js list ON');
console.log(' node dietitians.js profile SPECIALIST_ID');
console.log(
' node dietitians.js times SPECIALIST_ID SERVICE_ID America/Toronto [DAYS]',
);
}
} catch (error) {
if (!(error instanceof NurishdError)) throw error;
console.log(
`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
);
process.exit(1);
}
}
await main();// file: dietitians.ts
import { NurishdError, call } from './nurishd.ts';
import type { Page } from './nurishd.ts';
interface Specialist {
specialist_id: string;
specialist_first_name: string;
specialist_last_name: string;
specialist_specializations?: string[];
specialist_long_introduction?: string | null;
}
interface Service {
service_id: string;
service_name: string;
service_price_in_cents: number;
service_currency: string;
service_duration_in_minutes: number;
service_mode_of_delivery: string;
}
interface Availability {
slots?: { start_time: string; end_time: string }[];
}
function money(cents: number, currency: string) {
return `${(cents / 100).toFixed(2)} ${currency}`;
}
async function listServices(specialistId: string) {
const path = `/care/v1/specialist/${specialistId}/service/query/documents`;
const answer = await call<Page<Service>>('GET', path);
if (answer.data.length === 0) console.log(' no services');
for (const service of answer.data) {
const price = money(
service.service_price_in_cents,
service.service_currency,
);
console.log(
` service: ${service.service_name} (${service.service_id})`,
);
console.log(
` ${service.service_duration_in_minutes} minutes, ${price}, ` +
service.service_mode_of_delivery,
);
}
}
async function listDietitians(state: string) {
const answer = await call<Page<Specialist>>(
'GET',
'/care/v1/specialist/query/documents',
{ params: { type: 'Dietitian', state, size: 10 } },
);
for (const person of answer.data) {
const focus = (person.specialist_specializations ?? []).join(', ');
console.log(
`${person.specialist_first_name} ${person.specialist_last_name}`,
);
console.log(` id: ${person.specialist_id}`);
console.log(` focus: ${focus}`);
await listServices(person.specialist_id);
}
}
async function showProfile(specialistId: string) {
const person = await call<Specialist>(
'GET',
`/care/v1/specialist/${specialistId}/get/document`,
);
console.log(
`${person.specialist_first_name} ${person.specialist_last_name}`,
);
console.log(person.specialist_long_introduction ?? 'No introduction.');
}
async function showTimes(
specialistId: string,
serviceId: string,
zone: string,
days: number,
) {
const start = new Date();
const end = new Date(start.getTime() + days * 24 * 60 * 60 * 1000);
const path =
`/care/v1/specialist/${specialistId}/service/${serviceId}` +
'/availability/query/documents';
let answer: Availability;
try {
answer = await call<Availability>('GET', path, {
params: { from: start.toISOString(), to: end.toISOString() },
});
} catch (error) {
if (
error instanceof NurishdError &&
error.code === 'service_not_bookable'
) {
console.log(
'This service cannot be booked online. Choose another one.',
);
return;
}
throw error;
}
const dateFormat = new Intl.DateTimeFormat('en-CA', {
timeZone: zone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
const weekdayFormat = new Intl.DateTimeFormat('en-US', {
timeZone: zone,
weekday: 'long',
});
const timeFormat = new Intl.DateTimeFormat('en-GB', {
timeZone: zone,
hour: '2-digit',
minute: '2-digit',
});
const timesByDay = new Map<string, string[]>();
for (const slot of answer.slots ?? []) {
const moment = new Date(slot.start_time);
const day = `${weekdayFormat.format(moment)} ${dateFormat.format(moment)}`;
if (!timesByDay.has(day)) timesByDay.set(day, []);
timesByDay.get(day)?.push(timeFormat.format(moment));
}
if (timesByDay.size === 0) console.log('No open times in this range.');
for (const [day, times] of timesByDay) {
console.log(`${day}: ${times.join(', ')}`);
}
}
async function main() {
const args = process.argv.slice(2);
try {
if (args.length === 2 && args[0] === 'list') {
await listDietitians(args[1]);
} else if (args.length === 2 && args[0] === 'profile') {
await showProfile(args[1]);
} else if (
(args.length === 4 || args.length === 5) &&
args[0] === 'times'
) {
const days = args.length === 5 ? Number(args[4]) : 7;
await showTimes(args[1], args[2], args[3], days);
} else {
console.log('Usage:');
console.log(' node dietitians.js list ON');
console.log(' node dietitians.js profile SPECIALIST_ID');
console.log(
' node dietitians.js times SPECIALIST_ID SERVICE_ID America/Toronto [DAYS]',
);
}
} catch (error) {
if (!(error instanceof NurishdError)) throw error;
console.log(
`The API answered ${error.status} ${error.code} (request ${error.requestId}).`,
);
process.exit(1);
}
}
await main();// file: src/main/java/tutorial/Dietitians.java
package tutorial;
import com.fasterxml.jackson.databind.JsonNode;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import tutorial.Nurishd.NurishdException;
public class Dietitians {
static String money(long cents, String currency) {
return String.format("%.2f %s", cents / 100.0, currency);
}
static void listServices(String specialistId) {
String path = "/care/v1/specialist/%s/service/query/documents".formatted(specialistId);
JsonNode answer = Nurishd.call("GET", path);
if (answer.path("data").isEmpty()) {
System.out.println(" no services");
}
for (JsonNode service : answer.path("data")) {
String price = money(
service.path("service_price_in_cents").asLong(),
service.path("service_currency").asText());
System.out.println(" service: " + service.path("service_name").asText()
+ " (" + service.path("service_id").asText() + ")");
System.out.println(" " + service.path("service_duration_in_minutes").asInt()
+ " minutes, " + price + ", "
+ service.path("service_mode_of_delivery").asText());
}
}
static void listDietitians(String state) {
JsonNode answer = Nurishd.call(
"GET",
"/care/v1/specialist/query/documents",
Map.of("type", "Dietitian", "state", state, "size", 10),
null);
for (JsonNode person : answer.path("data")) {
List<String> focus = new ArrayList<>();
person.path("specialist_specializations").forEach(item -> focus.add(item.asText()));
System.out.println(person.path("specialist_first_name").asText() + " "
+ person.path("specialist_last_name").asText());
System.out.println(" id: " + person.path("specialist_id").asText());
System.out.println(" focus: " + String.join(", ", focus));
listServices(person.path("specialist_id").asText());
}
}
static void showProfile(String specialistId) {
JsonNode person =
Nurishd.call("GET", "/care/v1/specialist/%s/get/document".formatted(specialistId));
System.out.println(person.path("specialist_first_name").asText() + " "
+ person.path("specialist_last_name").asText());
System.out.println(person.path("specialist_long_introduction").asText("No introduction."));
}
static void showTimes(String specialistId, String serviceId, String zoneName, int days) {
ZoneId zone = ZoneId.of(zoneName);
Instant start = Instant.now().truncatedTo(ChronoUnit.SECONDS);
String path = "/care/v1/specialist/%s/service/%s/availability/query/documents"
.formatted(specialistId, serviceId);
JsonNode answer;
try {
answer = Nurishd.call(
"GET",
path,
Map.of("from", start.toString(), "to", start.plus(days, ChronoUnit.DAYS).toString()),
null);
} catch (NurishdException error) {
if (error.code.equals("service_not_bookable")) {
System.out.println("This service cannot be booked online. Choose another one.");
return;
}
throw error;
}
DateTimeFormatter dayFormat = DateTimeFormatter.ofPattern("EEEE yyyy-MM-dd", Locale.US);
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm");
Map<String, List<String>> timesByDay = new LinkedHashMap<>();
for (JsonNode slot : answer.path("slots")) {
ZonedDateTime local =
OffsetDateTime.parse(slot.path("start_time").asText()).atZoneSameInstant(zone);
timesByDay
.computeIfAbsent(dayFormat.format(local), day -> new ArrayList<>())
.add(timeFormat.format(local));
}
if (timesByDay.isEmpty()) {
System.out.println("No open times in this range.");
}
timesByDay.forEach((day, times) -> System.out.println(day + ": " + String.join(", ", times)));
}
public static void main(String[] args) {
try {
if (args.length == 2 && args[0].equals("list")) {
listDietitians(args[1]);
} else if (args.length == 2 && args[0].equals("profile")) {
showProfile(args[1]);
} else if ((args.length == 4 || args.length == 5) && args[0].equals("times")) {
int days = args.length == 5 ? Integer.parseInt(args[4]) : 7;
showTimes(args[1], args[2], args[3], days);
} else {
System.out.println("Usage:");
System.out.println(" list ON");
System.out.println(" profile SPECIALIST_ID");
System.out.println(" times SPECIALIST_ID SERVICE_ID America/Toronto [DAYS]");
}
} catch (NurishdException error) {
System.out.println("The API answered " + error.status + " " + error.code
+ " (request " + error.requestId + ").");
System.exit(1);
}
}
}If something goes wrong#
| What you see | Why | What to do |
|---|---|---|
403 scope_not_granted | The key does not hold specialist:read. | Use a key with the scope. See Scopes. |
401 invalid_api_key | The key is missing, wrong or revoked. | Check NURISHD_API_KEY. |
422 validation_error | A filter is wrong, for example a state that is not two capital letters. | Fix the argument. |
422 invalid_time_range | The range is empty, backwards or longer than 31 days. | Use 31 days or fewer. |
409 service_not_bookable | The service cannot be booked online. | Choose another service. The program prints a message. |
404 not_found | The dietitian does not exist, is not live, or is hidden. | Read the list again and use an id from it. |
| An empty list | No dietitian practises in that province, or none matches the filters. | Try another province. |
ZoneInfoNotFoundError or RangeError: Invalid time zone | The time zone name is wrong. | Use a name such as America/Toronto. In Python on Windows, run pip install tzdata. |
Serve the same data to your own page#
Your web page must never call the API with your key. Put the key on your server, and let the page call your server. To do that, wrap these functions in routes of your own, such as GET /dietitians?state=ON. Return the data as JSON instead of printing it, and send the times in UTC with the patient's time zone name so the page can convert them. The tutorial Receive order webhooks shows a small server in each language.
Next#
- Booking a visit: every filter, field and error of the booking routes.
- Book a visit with a dietitian: use an open time to book a visit.
- Pagination: read more than one page.
- Errors: every error code.
Something wrong on this page? Email hello@nurishd.io with the page address.