Developers

Search the docs

Search guides and headings.

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.

View as Markdown

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 nurishd client file and a Sandbox key in NURISHD_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.

python
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"])

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.

python
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.")

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.

python
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)}")

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.

python
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)

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:

text
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 Person

Copy 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.

text
python dietitians.py times 3b7d9a52-0000-4000-8000-0000000000a1 service-initial-consult America/Toronto 2

You see the days and the local times:

text
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:00

The 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:

text
python dietitians.py times 3b7d9a52-0000-4000-8000-0000000000a2 service-clinic America/Toronto
text
This service cannot be booked online. Choose another one.

The whole program#

python
# 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()

If something goes wrong#

What you seeWhyWhat to do
403 scope_not_grantedThe key does not hold specialist:read.Use a key with the scope. See Scopes.
401 invalid_api_keyThe key is missing, wrong or revoked.Check NURISHD_API_KEY.
422 validation_errorA filter is wrong, for example a state that is not two capital letters.Fix the argument.
422 invalid_time_rangeThe range is empty, backwards or longer than 31 days.Use 31 days or fewer.
409 service_not_bookableThe service cannot be booked online.Choose another service. The program prints a message.
404 not_foundThe dietitian does not exist, is not live, or is hidden.Read the list again and use an id from it.
An empty listNo dietitian practises in that province, or none matches the filters.Try another province.
ZoneInfoNotFoundError or RangeError: Invalid time zoneThe 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#