Developers

Search the docs

Search guides and headings.

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.

View as Markdown

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 nurishd client file and a Sandbox key in NURISHD_API_KEY.
  • Your key has the scopes patient:write, booking:write, booking:read and specialist: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.

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

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.

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

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"
text
Open this link in a browser and approve the connection:
https://app.nurishd.ca/connect/abc123

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

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

After you approve in the browser, run it again:

text
python visit.py status
Connection status: active

4. 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:

  1. Your server starts a setup with POST /care/v1/patient/{patient_id}/payment-method/setup/create/document. The answer holds a client_secret and a Stripe publishable key.
  2. 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.
  3. 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.

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

After the browser part and the confirm call, list the cards:

text
python visit.py cards
visa ending 4242 (default)

5. Book a visit#

POST /care/v1/booking/create/document needs these fields:

FieldWhat to send
userThe patient id from step 2.
specialist_idThe dietitian's id.
service_idThe service's id.
start_timeThe start_time of an open time, unchanged.
timezoneThe patient's time zone, such as America/Toronto.
client_noteOptional. 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.

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

The visit is booked. These are the statuses a booking can have:

StatusWhat it means
bookedThe visit is scheduled.
meeting_rescheduledThe visit was moved to another time.
meeting_completedThe visit took place.
meeting_cancelledThe visit was canceled.
no_showThe 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:

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

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

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

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

Run it again to see the refusal:

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

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

The whole program#

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

If something goes wrong#

What you seeWhyWhat to do
403 scope_not_grantedThe 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_grantedThe patient did not allow bookings.Create the patient again with a key that holds booking:write. Send the new link.
409 connection_not_activeThe 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_signedThe patient has not signed the agreements a visit needs.Run create again and send the patient to the new link.
409 payment_method_requiredThe patient has no saved card.Do step 4, then book again.
409 not_licensed_hereThe dietitian cannot serve this booking yet.Offer another dietitian. Check that the patient has an address.
409 slot_takenThe time is no longer open.Read the open times again and book another.
409 service_not_bookableThe service cannot be booked online, or the dietitian or service is unknown.Offer another service.
409 booking_not_cancelableThe booking is already canceled, completed or past.Run show to read its status.
409 external_id_conflictThe external_id already belongs to a patient with a different email.Keep the first email for this id.
422 validation_errorA field is wrong, for example a client_note with $, { or }.Fix the field. Do not send the same request again.
404 not_foundThe patient or booking does not exist, or belongs to another company.Check the ids in visit-state.json.

Next#