# Nurish'd Connect overview What Nurish'd Connect is, the three products it offers, and how a company gets access. Nurish'd Connect is the partner API for Nurish'd. After reading this page you know what you can build with it, how access works, and where to go next. ## What you can build A partner company calls one API at `https://api.dev.nurishd.ca`. Every call carries an API key in the `X-Partner-API-Key` header. Paths start with a product and a version: `/meals/v1`, `/care/v1`, `/developer/v1`. | Product | Path | What it does | Status | | --------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | | Meals | `/meals/v1` | Read vendors, menus, products, delivery zones and delivery dates. Connect a customer, save a card and place their orders. | Available. | | Care | `/care/v1` | Connect a patient, save a card, book visits with dietitians, read signed visit reports and a patient's health profile. | Available. Needs a signed BAA. | | Developer tools | `/developer/v1` | Check your API key, list events, manage webhook endpoints. | Available. | ## How a company gets access Access is by invitation only. There is no sign-up form. 1. Nurish'd creates your company and sets what it may do: its status, its scopes and, for care, its BAA. 2. Nurish'd invites one person as the owner. 3. The owner signs in to the console at `developer.nurishd.ca`, accepts the API terms, and invites up to four more members. A company has five seats, and pending invites count. 4. Members create API keys, register webhook endpoints and read events in the console. Read [Members and roles](/docs/console/members-and-roles) for who can do what. ## Two environments | | Sandbox | Production | | ------------------ | ------------------------------------ | ------------------------------------- | | Key prefix | `nk-test-` | `nk-prod-` | | Data | Fake people, simulated calendars | Real customers and patients | | Available | Once the owner accepts the API terms | Once Nurish'd marks your company Live | | Default rate limit | 25 calls per minute | 100 calls per minute | Both environments use the same base URL. The key decides which one you reach. See [Environments](/docs/get-started/environments). ## How the pieces fit - **Scopes** say what your company and each key may do. See [Scopes](/docs/concepts/scopes). - **Connections** are how a customer or patient agrees that your company may act for them. See [Connections](/docs/concepts/connections). - **Events** tell you what happened, with ids only. You fetch the object with your key. See [Events](/docs/events/events). - **Webhook endpoints** receive the same events by HTTPS. See [Webhooks](/docs/events/webhooks). ## Next - [Quickstart](/docs/get-started/quickstart): from invite to first call in five minutes. - [Environments](/docs/get-started/environments): what the Sandbox simulates. - [API reference](/reference): every operation, with a try-it panel. - [Swagger page](https://api.dev.nurishd.ca/docs): the same API on the API host. Read it and try calls with your own key. --- # Quickstart Go from an invite to your first Sandbox API call in five minutes. You will accept your invite, create a Sandbox API key, check that it works, and list vendors. It takes about five minutes. ## 1. Accept the invite Nurish'd emails the invite to the company owner. Open the link, sign in to your Nurish'd account (or create one), and use the same email address the invite was sent to. A forwarded invite does not work for another address. An invite expires after 7 days. ## 2. Accept the API terms The first time the owner signs in, the console asks them to accept the [Nurish'd API terms](https://www.nurishd.io/api-policy). No key can be created until they do. If you are not the owner, ask the owner to sign in first. ## 3. Create a Sandbox key 1. Open **API keys** in the console and make sure the environment switch says **Sandbox**. 2. Select **Create key** and give it a name. 3. Copy the key now. The full key is shown once and cannot be shown again. A key is a prefix and 64 hex characters, for example `nk-test-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef`. Put it in an environment variable. Do not put it in source code. ```bash export NURISHD_API_KEY="nk-test-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" ``` ## 4. Check the key `GET /developer/v1/key/get/document` returns the key you call it with. It needs no scope. ```bash curl https://api.dev.nurishd.ca/developer/v1/key/get/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/developer/v1/key/get/document', { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/developer/v1/key/get/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) print(res.status_code, res.json()) ``` The answer: ```json { "key_id": "key-0001", "name": "Quickstart", "mode": "test", "scopes": ["catalog:read", "order:read", "order:write"], "company_id": "company-0001", "company_name": "Example Foods", "company_status": "Sandbox", "rate_limit_per_minute": 25 } ``` `mode` is `test`, so you are in the Sandbox. `scopes` lists what this key may do now. `company_status` is `Sandbox`, `Live` or `Suspended`. If `catalog:read` is missing, ask Nurish'd to grant it to your company. If you get `401 invalid_api_key`, the key is missing, malformed, unknown, revoked or expired. All of these look the same. Check the header name and the copied value. ## 5. List vendors `GET /meals/v1/vendor/query/documents` needs the `catalog:read` scope. Use `size` to limit the page. ```bash curl "https://api.dev.nurishd.ca/meals/v1/vendor/query/documents?size=2" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/meals/v1/vendor/query/documents?size=2', { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/meals/v1/vendor/query/documents", params={"size": 2}, headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) print(res.status_code, res.json()) ``` The answer, trimmed to one vendor: ```json { "data": [ { "vendor_id": "vendor-0001", "vendor_name": "Green Table Kitchen", "vendor_logo_image": "https://images.example.com/vendor-0001/logo.png", "vendor_images": [], "vendor_short_description": "Fresh prepared meals.", "vendor_website_url": "https://greentable.example.com", "vendor_minimum_order_items": 4, "vendor_maximum_order_items": 40, "vendor_minimum_order_value": 6000, "vendor_maximum_order_value": null } ], "total_pages": 1, "total": 1, "page": 1, "size": 2, "has_next": false, "has_previous": false } ``` The list leaves out `vendor_long_description`, `vendor_timezone`, `vendor_address` and the support contact. Order values are in cents. Read one vendor with `GET /meals/v1/vendor/{vendor_id}/get/document` to get them. Every authenticated answer carries `RateLimit-Limit` and `RateLimit-Remaining`, and an `X-Request-Id` header. Keep the request id when you ask for [support](/docs/resources/support). ## Next - [Catalog](/docs/meals/catalog): find a zone for a place and read delivery dates. - [Authentication](/docs/concepts/authentication): store and roll keys safely. - [Errors](/docs/concepts/errors): every error code and what to do. --- # Environments What the Sandbox simulates, its limits, and the checklist for going live in Production. You will know how the Sandbox and Production differ, what the Sandbox fakes, and what to check before you go live. ## One URL, two environments Both environments use `https://api.dev.nurishd.ca`. The key you send decides where the call goes. The same host serves a [Swagger page](https://api.dev.nurishd.ca/docs) and the spec at `/openapi.json`. Both are open, so you need no key to read them. | | Sandbox | Production | | ------------------ | ------------------ | -------------------------------------------- | | Key prefix | `nk-test-` | `nk-prod-` | | `mode` in answers | `test` | `prod` | | People | Fake only | Real customers and patients | | Default rate limit | 25 per minute | 100 per minute | | Needs | Accepted API terms | Accepted API terms and a company marked Live | Keys, webhook endpoints and events belong to one environment. A Sandbox key never sees Production events, and a Production endpoint never receives Sandbox events. ## What the Sandbox simulates - **People are fake.** Customers and patients you create are test records. Never send real personal data to the Sandbox. - **Calendars are simulated.** Dietitian availability is generated: slots on weekdays from 9 to 5. They are not real calendars, and no video link works. See [Booking a visit](/docs/care/booking-a-visit). - **No email is delivered.** The connect page and the email-code sign-in accept the fixed code `424242` and send nothing. - **A visit does not finish by itself,** so no visit report appears on its own. > **Note.** The Sandbox test helper completes a booking and signs a sample report. It works with Sandbox keys only: a Production key gets `403 test_mode_only`. See [Visit reports](/docs/care/reports). ## Sandbox limits - The Sandbox rate limit is lower (25 per minute by default). - The code `424242` works only in the Sandbox. Production sends a real code to the email on the account. - Webhook delivery works as in Production, with Sandbox events only. See [Webhooks](/docs/events/webhooks). ## Going live checklist Nurish'd marks your company Live. Until then you cannot create a Production key. Before you ask: 1. Your company has accepted the API terms. 2. Your integration passes in the Sandbox, including the error paths in [Errors](/docs/concepts/errors). 3. You store keys in a secret manager and read them from environment variables. 4. You retry only the safe codes, with backoff, and honor `Retry-After`. See [Rate limits](/docs/concepts/rate-limits). 5. You verify webhook signatures and check the five minute tolerance. See [Verifying signatures](/docs/events/verifying-signatures). 6. You trust events or a fetched connection, never the `status` in a return URL. See [Connections](/docs/concepts/connections). 7. You registered your return URLs in the console. See [Company settings](/docs/console/company-settings). 8. You log `request_id` from every error. 9. For care: your company has a signed BAA. See [BAA handling](/docs/care/baa). Then email `hello@nurishd.io`. After Nurish'd marks the company Live, an owner or admin creates a Production key. ## Next - [Managing keys](/docs/console/managing-keys): create and roll keys per environment. - [Rate limits](/docs/concepts/rate-limits): limits per environment. - [Support](/docs/resources/support): contact and what to send. --- # Building with AI Plain Markdown, llms.txt and the OpenAPI file for coding assistants and LLMs. You will give a coding assistant or an LLM the right context to write code against Nurish'd Connect. ## What is available | Address | What it is | | ------------------------ | ------------------------------------------------------------------------------------------ | | Any docs page plus `.md` | The page as plain Markdown. `/docs/concepts/errors` is also at `/docs/concepts/errors.md`. | | `/llms.txt` | Every page with one line about what it covers, in the llmstxt.org format. | | `/llms-full.txt` | Every guide and the full API reference as one Markdown file. | | `/openapi.json` | The public OpenAPI document. It is the authority for paths, parameters and shapes. | All four are public. You do not need a key to read them. The API host also serves a [Swagger page](https://api.dev.nurishd.ca/docs), where a person can read the API and try calls with a key. ## Which to use - For a small task, paste one page's `.md` into the assistant, such as the page for the route you are calling. - For a larger task, give the assistant `/llms-full.txt`. It holds everything. - For generated clients or tools that read OpenAPI, use `/openapi.json`. ## A suggested prompt ```text You are writing code against the Nurish'd Connect partner API. The file llms-full.txt is attached. Treat it as the only source of truth. Rules: - Base URL is https://api.dev.nurishd.ca. Send the API key in the X-Partner-API-Key header. - Read the key from the NURISHD_API_KEY environment variable. Never hard-code a key. - Use only paths, parameters and fields that appear in the documentation. - Handle the error shape {"error": {"code", "message", "request_id"}} and log request_id. - Retry only 429, 502, 503 and 504, with backoff. Honor Retry-After. - Ignore fields and event types you do not know. Task: . ``` ## Check what it writes An assistant can invent a field or a path. Check generated code against the [API reference](/reference). Run it against the Sandbox first. Never paste a real key, a patient record or a customer's personal data into an assistant. ## Next - [Quickstart](/docs/get-started/quickstart): your first call by hand. - [Errors](/docs/concepts/errors): the codes your code must handle. - [API reference](/reference): the operations. --- # Set up your project Create a project in Python, JavaScript, TypeScript or Java that calls the Nurish'd Connect API with your Sandbox key. You will create a project folder, add a small API client, and run a first program. The program reads your API key, lists vendors and shows what an error looks like. Every other tutorial starts from this project. ## Before you start You need a language and a Sandbox API key. | Language | You need | | ---------- | ---------------------------------------------------------------------------- | | Python | Python 3.10 or newer. Check with `python --version`. | | JavaScript | Node 20 or newer. Check with `node --version`. | | TypeScript | Node 20 or newer, and Node 22.18 or newer to run `.ts` files directly. | | Java | Java 17 or newer and Maven. Check with `java --version` and `mvn --version`. | On Node older than 22.18, run TypeScript files with `npx tsx file.ts` instead of `node file.ts`. The tutorial shows both. A Sandbox API key starts with `nk-test-`. Create one in the console with the steps in the [Quickstart](/docs/get-started/quickstart). Copy it when it is shown. It is shown once. Your key needs the scope `catalog:read` for the program below. Other tutorials list the scopes they need. ## 1. Create the project Pick your language. Run the commands in a terminal. ### Python ```bash mkdir nurishd-tutorial cd nurishd-tutorial python -m venv .venv ``` Turn the virtual environment on. A virtual environment keeps this project's packages apart from the rest of your computer. - macOS and Linux: `source .venv/bin/activate` - Windows PowerShell: `.venv\Scripts\Activate.ps1` Your prompt now starts with `(.venv)`. Install the one package you need. `requests` sends HTTP calls. ```bash pip install requests ``` On some systems the commands are `python3` and `pip3`. Use those if `python` is not found. ### JavaScript ```bash mkdir nurishd-tutorial cd nurishd-tutorial npm init -y npm pkg set type=module ``` `type=module` lets you write `import` in `.js` files. You install no packages. Node has `fetch` built in. ### TypeScript ```bash mkdir nurishd-tutorial cd nurishd-tutorial npm init -y npm pkg set type=module npm install --save-dev typescript @types/node ``` TypeScript checks your types. `@types/node` teaches it about Node. Save this as `tsconfig.json` in the project folder: ```text { "compilerOptions": { "target": "es2022", "module": "nodenext", "strict": true, "noEmit": true, "allowImportingTsExtensions": true, "skipLibCheck": true, "types": ["node"] } } ``` ### Java Create the folders: ```bash mkdir -p nurishd-tutorial/src/main/java/tutorial cd nurishd-tutorial ``` On Windows PowerShell, use `mkdir nurishd-tutorial\src\main\java\tutorial` instead. Save this as `pom.xml` in the project folder. Maven reads it to find your Java version and the Jackson package, which reads JSON. ```xml 4.0.0 com.example nurishd-tutorial 1.0.0 17 UTF-8 com.fasterxml.jackson.core jackson-databind 2.17.2 org.codehaus.mojo exec-maven-plugin 3.4.1 ``` ## 2. Put your key in a variable The client reads your key from the `NURISHD_API_KEY` environment variable. An environment variable is a named value that lives in your terminal, outside your code. macOS and Linux: ```bash export NURISHD_API_KEY="nk-test-your-key-here" ``` Windows PowerShell: ```powershell $env:NURISHD_API_KEY = "nk-test-your-key-here" ``` Replace the text in quotes with your own key. The variable lasts until you close the terminal. Set it again in each new terminal. Never write a key in your source code or send it to a browser. Code gets committed and shared, and a key in it leaks. ## 3. Add the client Every tutorial calls the API through one small file. Save the file for your language in the project folder. For Java, save it as `src/main/java/tutorial/Nurishd.java`. ```python # file: nurishd.py """A small client for the Nurish'd Connect API.""" import os import time import requests API_URL = os.environ.get("NURISHD_API_URL", "https://api.dev.nurishd.ca") API_KEY = os.environ["NURISHD_API_KEY"] class NurishdError(Exception): """An error answer from the API.""" def __init__(self, status, code, message, request_id): super().__init__(f"{status} {code}: {message} (request {request_id})") self.status = status self.code = code self.message = message self.request_id = request_id def call(method, path, params=None, body=None): """Calls the API and returns the JSON answer. Waits once on a 429.""" for attempt in range(2): res = requests.request( method, API_URL + path, headers={"X-Partner-API-Key": API_KEY}, params=params, json=body, timeout=30, ) if res.status_code != 429 or attempt == 1: break time.sleep(int(res.headers.get("Retry-After", "5"))) if res.ok: return res.json() try: error = res.json()["error"] except (ValueError, KeyError): error = {"code": "unknown", "message": res.text[:200]} raise NurishdError( res.status_code, error.get("code"), error.get("message"), error.get("request_id") or res.headers.get("X-Request-Id"), ) def pages(path, params=None): """Yields every item of a list, one page at a time.""" page = 1 while True: answer = call("GET", path, {**(params or {}), "page": page}) yield from answer["data"] if not answer["has_next"]: return page += 1 ``` ```javascript // file: nurishd.js // A small client for the Nurish'd Connect API. const API_URL = process.env.NURISHD_API_URL ?? 'https://api.dev.nurishd.ca'; const API_KEY = process.env.NURISHD_API_KEY; if (!API_KEY) throw new Error('Set NURISHD_API_KEY first.'); /** An error answer from the API. */ export class NurishdError extends Error { constructor(status, code, message, requestId) { super(`${status} ${code}: ${message} (request ${requestId})`); this.status = status; this.code = code; this.requestId = requestId; } } /** Calls the API and returns the JSON answer. Waits once on a 429. */ export async function call(method, path, { params, body } = {}) { const url = new URL(API_URL + path); for (const [name, value] of Object.entries(params ?? {})) { for (const item of [value].flat()) { url.searchParams.append(name, String(item)); } } let res; for (let attempt = 0; attempt < 2; attempt++) { res = await fetch(url, { method, headers: { 'X-Partner-API-Key': API_KEY, ...(body ? { 'Content-Type': 'application/json' } : {}), }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(30_000), }); if (res.status !== 429 || attempt === 1) break; const seconds = Number(res.headers.get('Retry-After') ?? 5); await new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } const answer = await res.json().catch(() => null); if (res.ok) return answer; const error = answer?.error ?? { code: 'unknown', message: res.statusText }; throw new NurishdError( res.status, error.code, error.message, error.request_id ?? res.headers.get('X-Request-Id'), ); } /** Yields every item of a list, one page at a time. */ export async function* pages(path, params = {}) { for (let page = 1; ; page++) { const answer = await call('GET', path, { params: { ...params, page } }); yield* answer.data; if (!answer.has_next) return; } } ``` ```typescript // file: nurishd.ts // A small client for the Nurish'd Connect API. const API_URL = process.env.NURISHD_API_URL ?? 'https://api.dev.nurishd.ca'; const API_KEY = process.env.NURISHD_API_KEY ?? ''; if (!API_KEY) throw new Error('Set NURISHD_API_KEY first.'); type Method = 'GET' | 'POST' | 'PUT' | 'DELETE'; type Params = Record; /** One page of a list. */ export interface Page { data: T[]; total_pages: number; total: number; page: number; size: number; has_next: boolean; has_previous: boolean; } /** An error answer from the API. */ export class NurishdError extends Error { status: number; code: string; requestId: string | null; constructor( status: number, code: string, message: string, requestId: string | null, ) { super(`${status} ${code}: ${message} (request ${requestId})`); this.status = status; this.code = code; this.requestId = requestId; } } /** Calls the API and returns the JSON answer. Waits once on a 429. */ export async function call( method: Method, path: string, options: { params?: Params; body?: unknown } = {}, ): Promise { const url = new URL(API_URL + path); for (const [name, value] of Object.entries(options.params ?? {})) { for (const item of [value].flat()) { url.searchParams.append(name, String(item)); } } let res!: Response; for (let attempt = 0; attempt < 2; attempt++) { res = await fetch(url, { method, headers: { 'X-Partner-API-Key': API_KEY, ...(options.body ? { 'Content-Type': 'application/json' } : {}), }, body: options.body ? JSON.stringify(options.body) : undefined, signal: AbortSignal.timeout(30_000), }); if (res.status !== 429 || attempt === 1) break; const seconds = Number(res.headers.get('Retry-After') ?? 5); await new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } const answer = await res.json().catch(() => null); if (res.ok) return answer as T; const error = answer?.error ?? { code: 'unknown', message: res.statusText }; throw new NurishdError( res.status, error.code, error.message, error.request_id ?? res.headers.get('X-Request-Id'), ); } /** Yields every item of a list, one page at a time. */ export async function* pages( path: string, params: Params = {}, ): AsyncGenerator { for (let page = 1; ; page++) { const answer = await call>('GET', path, { params: { ...params, page }, }); yield* answer.data; if (!answer.has_next) return; } } ``` ```java // file: src/main/java/tutorial/Nurishd.java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** A small client for the Nurish'd Connect API. */ public final class Nurishd { public static final ObjectMapper JSON = new ObjectMapper(); private static final String API_URL = System.getenv().getOrDefault("NURISHD_API_URL", "https://api.dev.nurishd.ca"); private static final String API_KEY = System.getenv("NURISHD_API_KEY"); private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); private Nurishd() {} /** An error answer from the API. */ public static final class NurishdException extends RuntimeException { public final int status; public final String code; public final String requestId; NurishdException(int status, String code, String message, String requestId) { super(status + " " + code + ": " + message + " (request " + requestId + ")"); this.status = status; this.code = code; this.requestId = requestId; } } /** Calls the API with no query and no body. */ public static JsonNode call(String method, String path) { return call(method, path, Map.of(), null); } /** * Calls the API and returns the JSON answer. Waits once on a 429. A list in * {@code params} is sent as a repeated parameter; {@code body} may be null. */ public static JsonNode call(String method, String path, Map params, Object body) { if (API_KEY == null || API_KEY.isBlank()) { throw new IllegalStateException("Set NURISHD_API_KEY first."); } try { List query = new ArrayList<>(); for (Map.Entry entry : params.entrySet()) { List values = entry.getValue() instanceof List list ? list : List.of(entry.getValue()); for (Object value : values) { query.add(entry.getKey() + "=" + URLEncoder.encode(String.valueOf(value), StandardCharsets.UTF_8)); } } URI uri = URI.create(API_URL + path + (query.isEmpty() ? "" : "?" + String.join("&", query))); HttpRequest.Builder request = HttpRequest.newBuilder(uri) .timeout(Duration.ofSeconds(30)) .header("X-Partner-API-Key", API_KEY); if (body == null) { request.method(method, HttpRequest.BodyPublishers.noBody()); } else { request.header("Content-Type", "application/json") .method(method, HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body))); } HttpResponse res = null; for (int attempt = 0; attempt < 2; attempt++) { res = HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString()); if (res.statusCode() != 429 || attempt == 1) break; long seconds = Long.parseLong(res.headers().firstValue("Retry-After").orElse("5")); Thread.sleep(seconds * 1000); } JsonNode answer; try { answer = JSON.readTree(res.body()); } catch (IOException notJson) { answer = JSON.createObjectNode(); } if (res.statusCode() < 300) return answer; JsonNode error = answer.path("error"); throw new NurishdException( res.statusCode(), error.path("code").asText("unknown"), error.path("message").asText(res.body()), error.path("request_id") .asText(res.headers().firstValue("X-Request-Id").orElse(null))); } catch (IOException e) { throw new UncheckedIOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); } } /** Reads every page of a list and returns all its items. */ public static List pages(String path, Map params) { List items = new ArrayList<>(); for (int page = 1; ; page++) { Map query = new LinkedHashMap<>(params); query.put("page", page); JsonNode answer = call("GET", path, query, null); answer.path("data").forEach(items::add); if (!answer.path("has_next").asBoolean()) return items; } } } ``` The file gives you three things. - `call(method, path)` sends one request and returns the answer as JSON. It sends your key in the `X-Partner-API-Key` header. If the answer is `429 rate_limited`, it waits the number of seconds in the `Retry-After` header and tries once more. See [Rate limits](/docs/concepts/rate-limits). - When the API answers with an error, `call` raises an error object instead of returning. The object has the HTTP `status`, the `code` and the request id. Branch on `code`, not on the message. See [Errors](/docs/concepts/errors). - `pages(path)` reads a list one page at a time and hands you every item. It asks for page 1, then page 2, until the answer says there is no next page. See [Pagination](/docs/concepts/pagination). Three words you will see in every tutorial: - The path is the part of the address after the host, such as `/meals/v1/vendor/query/documents`. It says which thing you call. - A query parameter is an option added to the address, such as `size=2`. You pass them as `params`. - A JSON body is data you send with a `POST` or `PUT` call. You pass it as `body`. ## 4. Write the first program This program reads your key, lists the vendors two per page and then makes one call fail on purpose. Save the file for your language in the project folder. For Java, save it as `src/main/java/tutorial/CheckKey.java`. ```python # file: check_key.py from nurishd import NurishdError, call, pages # 1. Read the key you are calling with. key = call("GET", "/developer/v1/key/get/document") print("key:", key["name"]) print("mode:", key["mode"]) print("scopes:", ", ".join(key["scopes"])) # 2. List two vendors. size is how many items come in one page. for vendor in pages("/meals/v1/vendor/query/documents", {"size": 2}): print("vendor:", vendor["vendor_id"], vendor["vendor_name"]) # 3. Ask for too many items on purpose. The most a page can hold is 50. try: call("GET", "/meals/v1/vendor/query/documents", {"size": 500}) except NurishdError as error: print("refused:", error.status, error.code, error.request_id) ``` ```javascript // file: check_key.js import { NurishdError, call, pages } from './nurishd.js'; // 1. Read the key you are calling with. const key = await call('GET', '/developer/v1/key/get/document'); console.log('key:', key.name); console.log('mode:', key.mode); console.log('scopes:', key.scopes.join(', ')); // 2. List two vendors. size is how many items come in one page. for await (const vendor of pages('/meals/v1/vendor/query/documents', { size: 2, })) { console.log('vendor:', vendor.vendor_id, vendor.vendor_name); } // 3. Ask for too many items on purpose. The most a page can hold is 50. try { await call('GET', '/meals/v1/vendor/query/documents', { params: { size: 500 }, }); } catch (error) { if (!(error instanceof NurishdError)) throw error; console.log('refused:', error.status, error.code, error.requestId); } ``` ```typescript // file: check_key.ts import { NurishdError, call, pages } from './nurishd.ts'; interface Key { name: string; mode: 'test' | 'prod'; scopes: string[]; } interface Vendor { vendor_id: string; vendor_name: string; } // 1. Read the key you are calling with. const key = await call('GET', '/developer/v1/key/get/document'); console.log('key:', key.name); console.log('mode:', key.mode); console.log('scopes:', key.scopes.join(', ')); // 2. List two vendors. size is how many items come in one page. for await (const vendor of pages('/meals/v1/vendor/query/documents', { size: 2, })) { console.log('vendor:', vendor.vendor_id, vendor.vendor_name); } // 3. Ask for too many items on purpose. The most a page can hold is 50. try { await call('GET', '/meals/v1/vendor/query/documents', { params: { size: 500 }, }); } catch (error) { if (!(error instanceof NurishdError)) throw error; console.log('refused:', error.status, error.code, error.requestId); } ``` ```java // file: src/main/java/tutorial/CheckKey.java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.List; import java.util.Map; public class CheckKey { public static void main(String[] args) { // 1. Read the key you are calling with. JsonNode key = Nurishd.call("GET", "/developer/v1/key/get/document"); List scopes = new ArrayList<>(); key.path("scopes").forEach(scope -> scopes.add(scope.asText())); System.out.println("key: " + key.path("name").asText()); System.out.println("mode: " + key.path("mode").asText()); System.out.println("scopes: " + String.join(", ", scopes)); // 2. List two vendors. size is how many items come in one page. for (JsonNode vendor : Nurishd.pages("/meals/v1/vendor/query/documents", Map.of("size", 2))) { System.out.println("vendor: " + vendor.path("vendor_id").asText() + " " + vendor.path("vendor_name").asText()); } // 3. Ask for too many items on purpose. The most a page can hold is 50. try { Nurishd.call("GET", "/meals/v1/vendor/query/documents", Map.of("size", 500), null); } catch (Nurishd.NurishdException error) { System.out.println("refused: " + error.status + " " + error.code + " " + error.requestId); } } } ``` Step 1 calls `GET /developer/v1/key/get/document`. It returns the key you call with. Step 2 calls `GET /meals/v1/vendor/query/documents` through `pages`. Step 3 calls the same list with `size=500`. A page holds at most 50 items, so the API refuses the call. The program catches the error and prints it. ## 5. Run it Run the program for your language from the project folder. - Python: `python check_key.py` - JavaScript: `node check_key.js` - TypeScript: `node check_key.ts`, or `npx tsx check_key.ts` on Node older than 22.18. To check the types only, run `npx tsc`. - Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.CheckKey`. The first run downloads packages and takes a minute. You should see this. Your key name, vendors and request id differ. ```text key: Checkout server mode: test scopes: specialist:read, patient:write, booking:read, booking:write, report:read, health-profile:read, health-profile:write, catalog:read, order:read, order:write vendor: vendor-harbour-kitchen Harbour Kitchen refused: 422 validation_error req_14344b708031767a78e80b11a162dcbe ``` What each line means: - `key` is the name you gave the key in the console. - `mode: test` means the key belongs to the Sandbox. Everything you do with it uses fake data. A Production key prints `mode: prod`. See [Environments](/docs/get-started/environments). - `scopes` lists what this key may do. A call that needs a scope the key lacks fails with `403 scope_not_granted`. See [Scopes](/docs/concepts/scopes). - Each `vendor` line is one vendor. You asked for two per page, and `pages` kept reading until none were left. - `refused` is the error you caused on purpose. `422 validation_error` means something you sent broke a rule. Here it was the page size. Keep the request id when you ask [support](/docs/resources/support) for help. ## The whole program The files above are the whole program. Your project now holds these files. - Python: `nurishd.py` and `check_key.py` - JavaScript: `package.json`, `nurishd.js` and `check_key.js` - TypeScript: `package.json`, `tsconfig.json`, `nurishd.ts` and `check_key.ts` - Java: `pom.xml`, `src/main/java/tutorial/Nurishd.java` and `src/main/java/tutorial/CheckKey.java` ## If something goes wrong | What you see | Why | What to do | | ------------------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | `401 invalid_api_key` | The key is missing, mistyped, revoked or expired. | Copy the key again. Check that it starts with `nk-test-` and has no spaces or quotes inside. | | `403 scope_not_granted` | The key lacks a scope the call needs. | Read `scopes` in the output. Create a key with the scope, or ask Nurish'd to grant it to your company. | | `KeyError: 'NURISHD_API_KEY'` or `Set NURISHD_API_KEY first.` | The variable is not set in this terminal. | Run the command from step 2 again in the same terminal. | | `ModuleNotFoundError: No module named 'requests'` | The virtual environment is off. | Activate it and run `pip install requests`. | | `Cannot use import statement outside a module` | `package.json` has no `"type": "module"`. | Run `npm pkg set type=module`. | | `fetch is not defined` | Your Node is older than 18. | Install Node 20 or newer. | | `ERR_UNKNOWN_FILE_EXTENSION` for a `.ts` file | Your Node is older than 22.18. | Run `npx tsx check_key.ts`, or install a newer Node. | | `mvn: command not found` or `'mvn' is not recognized` | Maven is not installed or not on your path. | Install Maven, open a new terminal and run `mvn --version`. | | `release version 17 not supported` | Your Java is older than 17. | Install Java 17 or newer. | ## Next Pick the tutorial that matches what you build. - [Connect a customer](/docs/tutorials/connect-a-customer): link a customer to your company so you can order for them. - [Show meals for an address](/docs/tutorials/show-meals-for-an-address): find the vendors and meals that deliver to an address. - [Place a meal order](/docs/tutorials/place-a-meal-order): order meals for a connected customer and take the payment. - [Receive order webhooks](/docs/tutorials/receive-order-webhooks): build a server that Nurish'd calls when an order changes. - [Show dietitians](/docs/tutorials/show-dietitians): list the dietitians and their open times. - [Book a dietitian visit](/docs/tutorials/book-a-dietitian-visit): book a visit for a patient. - [Read visit reports](/docs/tutorials/read-visit-reports): read the report after a visit. - [Use Nurish'd with Shopify](/docs/tutorials/use-nurishd-with-shopify): connect a Shopify store to Nurish'd. --- # Connect a customer from your own sign-in Build a small web app that links a person who is signed in to your site with a Nurish'd meals customer, so your server can order for them. You will build a small web app. It sends a signed-in person to a Nurish'd page to approve, checks the answer when they come back, and remembers that they are connected. ## Single sign-on and the account link Nurish'd Connect has no SAML or OpenID single sign-on. It has an account link instead. Your site already knows who is signed in. You create a Nurish'd customer under your own id for that person, and you send them once to a Nurish'd page to approve. They come back to your site. After that your server acts for them with the API, and they never sign in to Nurish'd on your site. This is how the pieces map to what you know from single sign-on: | In single sign-on | In Nurish'd Connect | | ------------------------------ | ----------------------------------------- | | Your user id | `external_id`, your own id for the person | | The consent screen | The page at `connect_url`, shown once | | The redirect back to your site | Your `return_url` | | A valid session | A connection with the status `active` | A customer is a person you place meal orders for. The connection is their consent. ## Before you start - You finished [Set up your project](/docs/tutorials/set-up-your-project). Your project has the `nurishd` client file and a Sandbox key in `NURISHD_API_KEY`. - Your key has the scopes `order:write` and `order:read`. They are needed to create a customer and to read the connection. Run `check_key` from the setup tutorial to see your scopes. - A return URL is the address Nurish'd sends the person back to. It must start with `https://` and be registered in the console. Step 1 shows how to get one while you build. - Install the web server package for your language. | Language | Command | | ---------- | ------------------------------------------------------------------------ | | Python | `pip install flask` | | JavaScript | `npm install express` | | TypeScript | `npm install express` and `npm install --save-dev @types/express` | | Java | Replace `pom.xml` with the one below. It adds Javalin and a log package. | ## 1. Get a public address and register the return URL Nurish'd cannot send the browser back to `localhost`. While you build, a tunnel tool gives your computer a public HTTPS address that forwards to your server. Two common ones are ngrok and Cloudflare Tunnel. Follow their own setup guides, then start a tunnel to port 3000. - ngrok: `ngrok http 3000` - Cloudflare Tunnel: `cloudflared tunnel --url http://localhost:3000` The tool prints an address such as `https://example-name.trycloudflare.com`. Your return URL is that address plus `/nurishd/return`. Leave the tunnel running. Register the return URL in the console. See [Company settings](/docs/console/company-settings). A return URL that does not start with `https://` or is not on the list answers `422 validation_error`. The program reads the return URL from the `NURISHD_RETURN_URL` environment variable. Set it in the terminal where you run the program. Use your own address. - macOS and Linux: `export NURISHD_RETURN_URL="https://example-name.trycloudflare.com/nurishd/return"` - Windows PowerShell: `$env:NURISHD_RETURN_URL = "https://example-name.trycloudflare.com/nurishd/return"` ## 2. Add a stand-in for your sign-in This tutorial is about Nurish'd, so it does not build a sign-in. The program has one fixed signed-in user. A real app takes this user from its session. The `id` is your own id for the person. It becomes the `external_id`. The program also keeps what it learns about each user in memory. A real app uses its database. ```python app = Flask(__name__) # The return URL you registered in the console. It starts with https://. RETURN_URL = os.environ.get("NURISHD_RETURN_URL") if not RETURN_URL: raise SystemExit("Set NURISHD_RETURN_URL first.") # Stands in for your own sign-in. A real app reads this from its session. SIGNED_IN_USER = { "id": "customer-1001", "email": "ada.lovelace@example.com", "first_name": "Ada", "last_name": "Lovelace", } # What we know about each user's link, by user id. A real app uses its database. links = {} # A connection id goes into a URL path, so check its shape before you use it. CONNECTION_ID = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}") ``` ```javascript const app = express(); // The return URL you registered in the console. It starts with https://. const RETURN_URL = process.env.NURISHD_RETURN_URL ?? ''; if (!RETURN_URL) throw new Error('Set NURISHD_RETURN_URL first.'); // Stands in for your own sign-in. A real app reads this from its session. const signedInUser = { id: 'customer-1001', email: 'ada.lovelace@example.com', firstName: 'Ada', lastName: 'Lovelace', }; // What we know about each user's link, by user id. A real app uses its database. const links = new Map(); // A connection id goes into a URL path, so check its shape before you use it. const CONNECTION_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/; ``` ```typescript const app = express(); // The return URL you registered in the console. It starts with https://. const RETURN_URL = process.env.NURISHD_RETURN_URL ?? ''; if (!RETURN_URL) throw new Error('Set NURISHD_RETURN_URL first.'); // Stands in for your own sign-in. A real app reads this from its session. const signedInUser = { id: 'customer-1001', email: 'ada.lovelace@example.com', firstName: 'Ada', lastName: 'Lovelace', }; // What we know about each user's link, by user id. A real app uses its database. const links = new Map(); // A connection id goes into a URL path, so check its shape before you use it. const CONNECTION_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/; ``` ```java // The return URL you registered in the console. It starts with https://. static final String RETURN_URL = System.getenv("NURISHD_RETURN_URL"); // Stands in for your own sign-in. A real app reads this from its session. static final String USER_ID = "customer-1001"; static final String EMAIL = "ada.lovelace@example.com"; static final String FIRST_NAME = "Ada"; static final String LAST_NAME = "Lovelace"; // What we know about a user's link. record Link(String customerId, String connectionId, boolean connected) {} // The links by user id. A real app uses its database. static final Map links = new HashMap<>(); // A connection id goes into a URL path, so check its shape before you use it. static final Pattern CONNECTION_ID = Pattern.compile("[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}"); ``` `RETURN_URL` is the address you registered. The program stops with a message when `NURISHD_RETURN_URL` is not set. `CONNECTION_ID` is a check for step 5. ## 3. Turn a refusal into words Two answers of `POST /meals/v1/customer/create/document` are `409` refusals. Nothing is created. Each one needs a different message for the person. | Code | What it means | What to tell the person | | -------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------- | | `external_id_conflict` | Your id already belongs to a customer with a different email. | Their email changed. Ask them to contact your support. | | `person_already_connected` | This email is already connected to your company under a different id. | They have another account with you. Ask them to use that one. | Keep using the first `external_id` of a person. Do not make a new one. The helper `page` sends a small HTML answer. The helper `explain` picks the message. Any other error is printed for you, and the person sees a general message. ```python def page(text, status=200): return f"

{text}

", status def explain(error): if error.code == "external_id_conflict": return page("Your email changed. Contact support so we can fix the link.", 409) if error.code == "person_already_connected": return page("This email is already linked to another account. Sign in to that account.", 409) print(error) return page("We could not start the link. Try again later.", 502) ``` ```javascript function page(res, text, status = 200) { res.status(status).send(`

${text}

`); } function explain(res, error) { if (error.code === 'external_id_conflict') { return page( res, 'Your email changed. Contact support so we can fix the link.', 409, ); } if (error.code === 'person_already_connected') { return page( res, 'This email is already linked to another account. Sign in to that account.', 409, ); } console.log(error.message); return page(res, 'We could not start the link. Try again later.', 502); } ``` ```typescript function page(res: Response, text: string, status = 200) { res.status(status).send(`

${text}

`); } function explain(res: Response, error: NurishdError) { if (error.code === 'external_id_conflict') { return page( res, 'Your email changed. Contact support so we can fix the link.', 409, ); } if (error.code === 'person_already_connected') { return page( res, 'This email is already linked to another account. Sign in to that account.', 409, ); } console.log(error.message); return page(res, 'We could not start the link. Try again later.', 502); } ``` ```java static void page(Context ctx, String text, int status) { ctx.status(status).html("

" + text + "

"); } static void explain(Context ctx, NurishdException error) { if (error.code.equals("external_id_conflict")) { page(ctx, "Your email changed. Contact support so we can fix the link.", 409); } else if (error.code.equals("person_already_connected")) { page(ctx, "This email is already linked to another account. Sign in to that account.", 409); } else { System.out.println(error.getMessage()); page(ctx, "We could not start the link. Try again later.", 502); } } ``` ## 4. Start the link `GET /nurishd/connect` runs when the person presses a "Connect Nurish'd" button on your site. It calls `POST /meals/v1/customer/create/document` with the person's details and your `return_url`. The answer has three things you use: - `user` is the id of the customer. You use it later to place orders. - `connection.connection_id` is the id of the connection. - `connect_url` is the Nurish'd page where the person approves. The route stores the first two for this user and redirects the browser to `connect_url`. Open the link as a full page. Never put it in a frame or a web view, because the page refuses to load there. The link works once and for 24 hours. If the person waits too long, call create again with the same `external_id`. You get the same customer and a fresh link. `connect_url` is `null` when the person does not need to approve now. The route then goes straight to `/me`. ```python @app.get("/nurishd/connect") def connect(): user = SIGNED_IN_USER try: customer = call( "POST", "/meals/v1/customer/create/document", body={ "external_id": user["id"], "email": user["email"], "first_name": user["first_name"], "last_name": user["last_name"], "return_url": RETURN_URL, }, ) except NurishdError as error: return explain(error) connection = customer["connection"] links[user["id"]] = { "customer_id": customer["user"], "connection_id": connection["connection_id"], "connected": connection["status"] == "active", } if customer["connect_url"] is None: return redirect("/me") return redirect(customer["connect_url"]) ``` ```javascript app.get('/nurishd/connect', async (req, res) => { const user = signedInUser; let customer; try { customer = await call('POST', '/meals/v1/customer/create/document', { body: { external_id: user.id, email: user.email, first_name: user.firstName, last_name: user.lastName, return_url: RETURN_URL, }, }); } catch (error) { if (!(error instanceof NurishdError)) throw error; return explain(res, error); } links.set(user.id, { customerId: customer.user, connectionId: customer.connection.connection_id, connected: customer.connection.status === 'active', }); if (customer.connect_url === null) return res.redirect('/me'); res.redirect(customer.connect_url); }); ``` ```typescript app.get('/nurishd/connect', async (req, res) => { const user = signedInUser; let customer: Customer; try { customer = await call( 'POST', '/meals/v1/customer/create/document', { body: { external_id: user.id, email: user.email, first_name: user.firstName, last_name: user.lastName, return_url: RETURN_URL, }, }, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; return explain(res, error); } links.set(user.id, { customerId: customer.user, connectionId: customer.connection.connection_id, connected: customer.connection.status === 'active', }); if (customer.connect_url === null) return res.redirect('/me'); res.redirect(customer.connect_url); }); ``` ```java static void connect(Context ctx) { JsonNode customer; try { customer = Nurishd.call( "POST", "/meals/v1/customer/create/document", Map.of(), Map.of( "external_id", USER_ID, "email", EMAIL, "first_name", FIRST_NAME, "last_name", LAST_NAME, "return_url", RETURN_URL)); } catch (NurishdException error) { explain(ctx, error); return; } JsonNode connection = customer.path("connection"); links.put(USER_ID, new Link( customer.path("user").asText(), connection.path("connection_id").asText(), connection.path("status").asText().equals("active"))); if (customer.path("connect_url").isNull()) { ctx.redirect("/me"); } else { ctx.redirect(customer.path("connect_url").asText()); } } ``` ## 5. Handle the return The person approves on the Nurish'd page. Then Nurish'd sends the browser to your `return_url` with `connection_id` and `status` in the query, for example `/nurishd/return?connection_id=connection-0001&status=approved`. Never trust that `status`. Anyone can type a URL. The route does three checks instead: 1. It checks the shape of `connection_id`, because the id goes into a URL path. 2. It reads the connection with `GET /meals/v1/connection/{connection_id}/get/document`. The answer comes from Nurish'd, so you can trust it. 3. It checks that the connection's `external_id` is the signed-in user's id. This refuses a person who pastes the id of someone else's connection. Only then does it look at the `status` of the connection it read. The connection has one of four statuses: | Status | The page says | | ---------- | ------------------------------ | | `active` | The person is connected. | | `pending` | Not approved yet. Start again. | | `declined` | The person declined. | | `revoked` | The link ended. Start again. | Only `active` marks the user as connected. ```python @app.get("/nurishd/return") def come_back(): user = SIGNED_IN_USER connection_id = request.args.get("connection_id", "") if not CONNECTION_ID.fullmatch(connection_id): return page("This link is not valid.", 400) try: connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document") except NurishdError as error: if error.status == 404: return page("We do not know this connection.", 404) print(error) return page("We could not check the connection.", 502) if connection["external_id"] != user["id"]: return page("This connection belongs to someone else.", 403) if connection["status"] == "active": links[user["id"]] = { "customer_id": connection["user"], "connection_id": connection["connection_id"], "connected": True, } return page("You are connected to Nurish'd.") if connection["status"] == "pending": return page("Not approved yet. Go to /nurishd/connect for a new link.") if connection["status"] == "declined": return page("You declined the link. Go to /nurishd/connect to start again.") return page("The link ended. Go to /nurishd/connect to start again.") ``` ```javascript app.get('/nurishd/return', async (req, res) => { const user = signedInUser; const connectionId = String(req.query.connection_id ?? ''); if (!CONNECTION_ID.test(connectionId)) { return page(res, 'This link is not valid.', 400); } let connection; try { connection = await call( 'GET', `/meals/v1/connection/${connectionId}/get/document`, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; if (error.status === 404) { return page(res, 'We do not know this connection.', 404); } console.log(error.message); return page(res, 'We could not check the connection.', 502); } if (connection.external_id !== user.id) { return page(res, 'This connection belongs to someone else.', 403); } if (connection.status === 'active') { links.set(user.id, { customerId: connection.user, connectionId: connection.connection_id, connected: true, }); return page(res, "You are connected to Nurish'd."); } if (connection.status === 'pending') { return page( res, 'Not approved yet. Go to /nurishd/connect for a new link.', ); } if (connection.status === 'declined') { return page( res, 'You declined the link. Go to /nurishd/connect to start again.', ); } page(res, 'The link ended. Go to /nurishd/connect to start again.'); }); ``` ```typescript app.get('/nurishd/return', async (req, res) => { const user = signedInUser; const connectionId = String(req.query.connection_id ?? ''); if (!CONNECTION_ID.test(connectionId)) { return page(res, 'This link is not valid.', 400); } let connection: Connection; try { connection = await call( 'GET', `/meals/v1/connection/${connectionId}/get/document`, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; if (error.status === 404) { return page(res, 'We do not know this connection.', 404); } console.log(error.message); return page(res, 'We could not check the connection.', 502); } if (connection.external_id !== user.id) { return page(res, 'This connection belongs to someone else.', 403); } if (connection.status === 'active') { links.set(user.id, { customerId: connection.user, connectionId: connection.connection_id, connected: true, }); return page(res, "You are connected to Nurish'd."); } if (connection.status === 'pending') { return page( res, 'Not approved yet. Go to /nurishd/connect for a new link.', ); } if (connection.status === 'declined') { return page( res, 'You declined the link. Go to /nurishd/connect to start again.', ); } page(res, 'The link ended. Go to /nurishd/connect to start again.'); }); ``` ```java static void comeBack(Context ctx) { String connectionId = ctx.queryParamAsClass("connection_id", String.class).getOrDefault(""); if (!CONNECTION_ID.matcher(connectionId).matches()) { page(ctx, "This link is not valid.", 400); return; } JsonNode connection; try { connection = Nurishd.call("GET", "/meals/v1/connection/%s/get/document".formatted(connectionId)); } catch (NurishdException error) { if (error.status == 404) { page(ctx, "We do not know this connection.", 404); return; } System.out.println(error.getMessage()); page(ctx, "We could not check the connection.", 502); return; } if (!connection.path("external_id").asText().equals(USER_ID)) { page(ctx, "This connection belongs to someone else.", 403); return; } String status = connection.path("status").asText(); if (status.equals("active")) { links.put(USER_ID, new Link( connection.path("user").asText(), connection.path("connection_id").asText(), true)); page(ctx, "You are connected to Nurish'd.", 200); } else if (status.equals("pending")) { page(ctx, "Not approved yet. Go to /nurishd/connect for a new link.", 200); } else if (status.equals("declined")) { page(ctx, "You declined the link. Go to /nurishd/connect to start again.", 200); } else { page(ctx, "The link ended. Go to /nurishd/connect to start again.", 200); } } ``` ## 6. Show the state `GET /me` answers from what the program stored. After this, your pages and your order code check this state before they act for the person. The last lines start the server on port 3000. ```python @app.get("/me") def me(): user = SIGNED_IN_USER if links.get(user["id"], {}).get("connected"): return page(f"{user['first_name']}, you are connected to Nurish'd.") return page(f"{user['first_name']}, you are not connected yet. Go to /nurishd/connect.") app.run(port=3000) ``` ```javascript app.get('/me', (req, res) => { const user = signedInUser; if (links.get(user.id)?.connected) { return page(res, `${user.firstName}, you are connected to Nurish'd.`); } page( res, `${user.firstName}, you are not connected yet. Go to /nurishd/connect.`, ); }); app.listen(3000, () => console.log('Listening on http://localhost:3000')); ``` ```typescript app.get('/me', (req, res) => { const user = signedInUser; if (links.get(user.id)?.connected) { return page(res, `${user.firstName}, you are connected to Nurish'd.`); } page( res, `${user.firstName}, you are not connected yet. Go to /nurishd/connect.`, ); }); app.listen(3000, () => console.log('Listening on http://localhost:3000')); ``` ```java static void me(Context ctx) { Link link = links.get(USER_ID); if (link != null && link.connected()) { page(ctx, FIRST_NAME + ", you are connected to Nurish'd.", 200); } else { page(ctx, FIRST_NAME + ", you are not connected yet. Go to /nurishd/connect.", 200); } } public static void main(String[] args) { if (RETURN_URL == null || RETURN_URL.isBlank()) { System.out.println("Set NURISHD_RETURN_URL first."); System.exit(1); } Javalin app = Javalin.create(); app.get("/nurishd/connect", Connect::connect); app.get("/nurishd/return", Connect::comeBack); app.get("/me", Connect::me); app.start(3000); } } ``` ## 7. Run it Start the server. | Language | Command | | ---------- | ------------------------------------------------------------ | | Python | `python connect.py` | | JavaScript | `node connect.js` | | TypeScript | `node connect.ts` | | Java | `mvn -q compile exec:java -Dexec.mainClass=tutorial.Connect` | Open your tunnel address in a browser, for example `https://example-name.trycloudflare.com/me`. It says you are not connected. Then open `https://example-name.trycloudflare.com/nurishd/connect`. The browser goes to the Nurish'd page. Use the tunnel address and not `localhost`, because Nurish'd sends the browser back to the address you registered. In the Sandbox, no email is sent. The approval page accepts the code `424242`. See [Environments](/docs/get-started/environments). After you approve, the browser lands on `/nurishd/return` and the page says you are connected. Open `/me` again to see the stored state. To see the redirect without a browser, ask your server for the route with `curl` on `localhost`. ```bash curl -i http://localhost:3000/nurishd/connect ``` Among the headers you see the status `302` and a `Location` header. It holds the `connect_url` of your customer. ```text HTTP/1.1 302 Found Location: https://connect.example.com/approve/8f3k2m9q7x4z ``` Now call the return route with the connection id the create call answered. Then call it with an id that does not exist. ```bash curl -i "http://localhost:3000/nurishd/return?connection_id=connection-0001&status=approved" curl -i "http://localhost:3000/nurishd/return?connection_id=missing-1&status=approved" ``` ```text HTTP/1.1 200 OK

You are connected to Nurish'd.

HTTP/1.1 404 Not Found

We do not know this connection.

``` ## The same for a care patient The flow for a care patient is the same. You call `POST /care/v1/patient/create/document` and read the connection with `GET /care/v1/connection/{connection_id}/get/document`. A patient also needs a date of birth and an address. See [Connecting a patient](/docs/care/connecting-a-patient). To use a connected patient, follow [Book a dietitian visit](/docs/tutorials/book-a-dietitian-visit). ## Do not wait for the browser The person may close the tab before they return to your site. The `connection.approved` event tells your server the same thing without the browser. See [Receive order webhooks](/docs/tutorials/receive-order-webhooks) and [Events](/docs/events/events). ## The whole program ```python # file: connect.py import os import re from flask import Flask, redirect, request from nurishd import NurishdError, call app = Flask(__name__) # The return URL you registered in the console. It starts with https://. RETURN_URL = os.environ.get("NURISHD_RETURN_URL") if not RETURN_URL: raise SystemExit("Set NURISHD_RETURN_URL first.") # Stands in for your own sign-in. A real app reads this from its session. SIGNED_IN_USER = { "id": "customer-1001", "email": "ada.lovelace@example.com", "first_name": "Ada", "last_name": "Lovelace", } # What we know about each user's link, by user id. A real app uses its database. links = {} # A connection id goes into a URL path, so check its shape before you use it. CONNECTION_ID = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}") def page(text, status=200): return f"

{text}

", status def explain(error): if error.code == "external_id_conflict": return page("Your email changed. Contact support so we can fix the link.", 409) if error.code == "person_already_connected": return page("This email is already linked to another account. Sign in to that account.", 409) print(error) return page("We could not start the link. Try again later.", 502) @app.get("/nurishd/connect") def connect(): user = SIGNED_IN_USER try: customer = call( "POST", "/meals/v1/customer/create/document", body={ "external_id": user["id"], "email": user["email"], "first_name": user["first_name"], "last_name": user["last_name"], "return_url": RETURN_URL, }, ) except NurishdError as error: return explain(error) connection = customer["connection"] links[user["id"]] = { "customer_id": customer["user"], "connection_id": connection["connection_id"], "connected": connection["status"] == "active", } if customer["connect_url"] is None: return redirect("/me") return redirect(customer["connect_url"]) @app.get("/nurishd/return") def come_back(): user = SIGNED_IN_USER connection_id = request.args.get("connection_id", "") if not CONNECTION_ID.fullmatch(connection_id): return page("This link is not valid.", 400) try: connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document") except NurishdError as error: if error.status == 404: return page("We do not know this connection.", 404) print(error) return page("We could not check the connection.", 502) if connection["external_id"] != user["id"]: return page("This connection belongs to someone else.", 403) if connection["status"] == "active": links[user["id"]] = { "customer_id": connection["user"], "connection_id": connection["connection_id"], "connected": True, } return page("You are connected to Nurish'd.") if connection["status"] == "pending": return page("Not approved yet. Go to /nurishd/connect for a new link.") if connection["status"] == "declined": return page("You declined the link. Go to /nurishd/connect to start again.") return page("The link ended. Go to /nurishd/connect to start again.") @app.get("/me") def me(): user = SIGNED_IN_USER if links.get(user["id"], {}).get("connected"): return page(f"{user['first_name']}, you are connected to Nurish'd.") return page(f"{user['first_name']}, you are not connected yet. Go to /nurishd/connect.") app.run(port=3000) ``` ```javascript // file: connect.js import express from 'express'; import { NurishdError, call } from './nurishd.js'; const app = express(); // The return URL you registered in the console. It starts with https://. const RETURN_URL = process.env.NURISHD_RETURN_URL ?? ''; if (!RETURN_URL) throw new Error('Set NURISHD_RETURN_URL first.'); // Stands in for your own sign-in. A real app reads this from its session. const signedInUser = { id: 'customer-1001', email: 'ada.lovelace@example.com', firstName: 'Ada', lastName: 'Lovelace', }; // What we know about each user's link, by user id. A real app uses its database. const links = new Map(); // A connection id goes into a URL path, so check its shape before you use it. const CONNECTION_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/; function page(res, text, status = 200) { res.status(status).send(`

${text}

`); } function explain(res, error) { if (error.code === 'external_id_conflict') { return page( res, 'Your email changed. Contact support so we can fix the link.', 409, ); } if (error.code === 'person_already_connected') { return page( res, 'This email is already linked to another account. Sign in to that account.', 409, ); } console.log(error.message); return page(res, 'We could not start the link. Try again later.', 502); } app.get('/nurishd/connect', async (req, res) => { const user = signedInUser; let customer; try { customer = await call('POST', '/meals/v1/customer/create/document', { body: { external_id: user.id, email: user.email, first_name: user.firstName, last_name: user.lastName, return_url: RETURN_URL, }, }); } catch (error) { if (!(error instanceof NurishdError)) throw error; return explain(res, error); } links.set(user.id, { customerId: customer.user, connectionId: customer.connection.connection_id, connected: customer.connection.status === 'active', }); if (customer.connect_url === null) return res.redirect('/me'); res.redirect(customer.connect_url); }); app.get('/nurishd/return', async (req, res) => { const user = signedInUser; const connectionId = String(req.query.connection_id ?? ''); if (!CONNECTION_ID.test(connectionId)) { return page(res, 'This link is not valid.', 400); } let connection; try { connection = await call( 'GET', `/meals/v1/connection/${connectionId}/get/document`, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; if (error.status === 404) { return page(res, 'We do not know this connection.', 404); } console.log(error.message); return page(res, 'We could not check the connection.', 502); } if (connection.external_id !== user.id) { return page(res, 'This connection belongs to someone else.', 403); } if (connection.status === 'active') { links.set(user.id, { customerId: connection.user, connectionId: connection.connection_id, connected: true, }); return page(res, "You are connected to Nurish'd."); } if (connection.status === 'pending') { return page( res, 'Not approved yet. Go to /nurishd/connect for a new link.', ); } if (connection.status === 'declined') { return page( res, 'You declined the link. Go to /nurishd/connect to start again.', ); } page(res, 'The link ended. Go to /nurishd/connect to start again.'); }); app.get('/me', (req, res) => { const user = signedInUser; if (links.get(user.id)?.connected) { return page(res, `${user.firstName}, you are connected to Nurish'd.`); } page( res, `${user.firstName}, you are not connected yet. Go to /nurishd/connect.`, ); }); app.listen(3000, () => console.log('Listening on http://localhost:3000')); ``` ```typescript // file: connect.ts import express, { type Response } from 'express'; import { NurishdError, call } from './nurishd.ts'; interface Connection { connection_id: string; user: string; external_id: string; status: 'pending' | 'active' | 'declined' | 'revoked'; } interface Customer { user: string; connection: Connection; connect_url: string | null; } interface Link { customerId: string; connectionId: string; connected: boolean; } const app = express(); // The return URL you registered in the console. It starts with https://. const RETURN_URL = process.env.NURISHD_RETURN_URL ?? ''; if (!RETURN_URL) throw new Error('Set NURISHD_RETURN_URL first.'); // Stands in for your own sign-in. A real app reads this from its session. const signedInUser = { id: 'customer-1001', email: 'ada.lovelace@example.com', firstName: 'Ada', lastName: 'Lovelace', }; // What we know about each user's link, by user id. A real app uses its database. const links = new Map(); // A connection id goes into a URL path, so check its shape before you use it. const CONNECTION_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/; function page(res: Response, text: string, status = 200) { res.status(status).send(`

${text}

`); } function explain(res: Response, error: NurishdError) { if (error.code === 'external_id_conflict') { return page( res, 'Your email changed. Contact support so we can fix the link.', 409, ); } if (error.code === 'person_already_connected') { return page( res, 'This email is already linked to another account. Sign in to that account.', 409, ); } console.log(error.message); return page(res, 'We could not start the link. Try again later.', 502); } app.get('/nurishd/connect', async (req, res) => { const user = signedInUser; let customer: Customer; try { customer = await call( 'POST', '/meals/v1/customer/create/document', { body: { external_id: user.id, email: user.email, first_name: user.firstName, last_name: user.lastName, return_url: RETURN_URL, }, }, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; return explain(res, error); } links.set(user.id, { customerId: customer.user, connectionId: customer.connection.connection_id, connected: customer.connection.status === 'active', }); if (customer.connect_url === null) return res.redirect('/me'); res.redirect(customer.connect_url); }); app.get('/nurishd/return', async (req, res) => { const user = signedInUser; const connectionId = String(req.query.connection_id ?? ''); if (!CONNECTION_ID.test(connectionId)) { return page(res, 'This link is not valid.', 400); } let connection: Connection; try { connection = await call( 'GET', `/meals/v1/connection/${connectionId}/get/document`, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; if (error.status === 404) { return page(res, 'We do not know this connection.', 404); } console.log(error.message); return page(res, 'We could not check the connection.', 502); } if (connection.external_id !== user.id) { return page(res, 'This connection belongs to someone else.', 403); } if (connection.status === 'active') { links.set(user.id, { customerId: connection.user, connectionId: connection.connection_id, connected: true, }); return page(res, "You are connected to Nurish'd."); } if (connection.status === 'pending') { return page( res, 'Not approved yet. Go to /nurishd/connect for a new link.', ); } if (connection.status === 'declined') { return page( res, 'You declined the link. Go to /nurishd/connect to start again.', ); } page(res, 'The link ended. Go to /nurishd/connect to start again.'); }); app.get('/me', (req, res) => { const user = signedInUser; if (links.get(user.id)?.connected) { return page(res, `${user.firstName}, you are connected to Nurish'd.`); } page( res, `${user.firstName}, you are not connected yet. Go to /nurishd/connect.`, ); }); app.listen(3000, () => console.log('Listening on http://localhost:3000')); ``` ```java // file: src/main/java/tutorial/Connect.java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import io.javalin.Javalin; import io.javalin.http.Context; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import tutorial.Nurishd.NurishdException; public class Connect { // The return URL you registered in the console. It starts with https://. static final String RETURN_URL = System.getenv("NURISHD_RETURN_URL"); // Stands in for your own sign-in. A real app reads this from its session. static final String USER_ID = "customer-1001"; static final String EMAIL = "ada.lovelace@example.com"; static final String FIRST_NAME = "Ada"; static final String LAST_NAME = "Lovelace"; // What we know about a user's link. record Link(String customerId, String connectionId, boolean connected) {} // The links by user id. A real app uses its database. static final Map links = new HashMap<>(); // A connection id goes into a URL path, so check its shape before you use it. static final Pattern CONNECTION_ID = Pattern.compile("[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}"); static void page(Context ctx, String text, int status) { ctx.status(status).html("

" + text + "

"); } static void explain(Context ctx, NurishdException error) { if (error.code.equals("external_id_conflict")) { page(ctx, "Your email changed. Contact support so we can fix the link.", 409); } else if (error.code.equals("person_already_connected")) { page(ctx, "This email is already linked to another account. Sign in to that account.", 409); } else { System.out.println(error.getMessage()); page(ctx, "We could not start the link. Try again later.", 502); } } static void connect(Context ctx) { JsonNode customer; try { customer = Nurishd.call( "POST", "/meals/v1/customer/create/document", Map.of(), Map.of( "external_id", USER_ID, "email", EMAIL, "first_name", FIRST_NAME, "last_name", LAST_NAME, "return_url", RETURN_URL)); } catch (NurishdException error) { explain(ctx, error); return; } JsonNode connection = customer.path("connection"); links.put(USER_ID, new Link( customer.path("user").asText(), connection.path("connection_id").asText(), connection.path("status").asText().equals("active"))); if (customer.path("connect_url").isNull()) { ctx.redirect("/me"); } else { ctx.redirect(customer.path("connect_url").asText()); } } static void comeBack(Context ctx) { String connectionId = ctx.queryParamAsClass("connection_id", String.class).getOrDefault(""); if (!CONNECTION_ID.matcher(connectionId).matches()) { page(ctx, "This link is not valid.", 400); return; } JsonNode connection; try { connection = Nurishd.call("GET", "/meals/v1/connection/%s/get/document".formatted(connectionId)); } catch (NurishdException error) { if (error.status == 404) { page(ctx, "We do not know this connection.", 404); return; } System.out.println(error.getMessage()); page(ctx, "We could not check the connection.", 502); return; } if (!connection.path("external_id").asText().equals(USER_ID)) { page(ctx, "This connection belongs to someone else.", 403); return; } String status = connection.path("status").asText(); if (status.equals("active")) { links.put(USER_ID, new Link( connection.path("user").asText(), connection.path("connection_id").asText(), true)); page(ctx, "You are connected to Nurish'd.", 200); } else if (status.equals("pending")) { page(ctx, "Not approved yet. Go to /nurishd/connect for a new link.", 200); } else if (status.equals("declined")) { page(ctx, "You declined the link. Go to /nurishd/connect to start again.", 200); } else { page(ctx, "The link ended. Go to /nurishd/connect to start again.", 200); } } static void me(Context ctx) { Link link = links.get(USER_ID); if (link != null && link.connected()) { page(ctx, FIRST_NAME + ", you are connected to Nurish'd.", 200); } else { page(ctx, FIRST_NAME + ", you are not connected yet. Go to /nurishd/connect.", 200); } } public static void main(String[] args) { if (RETURN_URL == null || RETURN_URL.isBlank()) { System.out.println("Set NURISHD_RETURN_URL first."); System.exit(1); } Javalin app = Javalin.create(); app.get("/nurishd/connect", Connect::connect); app.get("/nurishd/return", Connect::comeBack); app.get("/me", Connect::me); app.start(3000); } } ``` ```xml 4.0.0 com.example nurishd-tutorial 1.0.0 17 UTF-8 com.fasterxml.jackson.core jackson-databind 2.17.2 io.javalin javalin 6.3.0 org.slf4j slf4j-simple 2.0.16 org.codehaus.mojo exec-maven-plugin 3.4.1 ``` ## If something goes wrong | What you see | Why | What to do | | ----------------------------------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `409 external_id_conflict` on create | The `external_id` belongs to a customer with another email. | Keep using the first id of the person. Do not change it. | | `409 person_already_connected` on create | The email is connected under another `external_id`. | Use the id you first gave to this person. | | `422 validation_error` on create | A field is wrong, or the return URL is not `https` or not registered. | Register the return URL in the console. Use the tunnel address, not `http` or `localhost`. Check the email. | | `Set NURISHD_RETURN_URL first.` | The variable is not set in this terminal. | Run the `export` or `$env` command from step 1 again in the same terminal. | | `403 scope_not_granted` | Your key lacks `order:write` or `order:read`. | Create a key with both scopes. | | `404 not_found` when you read the connection | The id does not exist, or it belongs to another environment. | Use the `connection.connection_id` of the create answer in the same Sandbox. | | The Nurish'd page does not open or says the link used | The link works once and for 24 hours, or it was in a frame. | Open `/nurishd/connect` again for a fresh link. Open it as a full page. | ## Next - [Customers](/docs/meals/customers): every customer route. - [Connections](/docs/concepts/connections): statuses, scopes and return URLs. - [Show meals for an address and a date](/docs/tutorials/show-meals-for-an-address): find what to order. - [Place a meal order](/docs/tutorials/place-a-meal-order): order for a connected customer. --- # Show meals for an address and a date Write a command-line program that lists the vendors that deliver to a place, their next delivery dates, and the meals with prices on one date. You will write a command-line program. You give it a city, a province and a country, and optionally a date. It prints the vendors that deliver there, the next delivery dates of each vendor, and the meals each vendor offers on one date, with their prices. ## Before you start - You finished [Set up your project](/docs/tutorials/set-up-your-project). Your project has the `nurishd` client file and a Sandbox key in `NURISHD_API_KEY`. - Your key has the scope `catalog:read`. Every call in this tutorial needs it. Run `check_key` from the setup tutorial to see your scopes. - You need no extra package. Take the city, the province and the country from the customer's delivery address. The street and the postal code are not used for this lookup. You send the whole address later, when you place the order. The place lookup takes a city, a province and a country. It does not take a postal code. The province and the country are two capital letters, such as `ON` and `CA`. The city must match what the vendor stored, letter for letter. `Toronto` does not find a zone stored as `toronto`. ## How the calls fit together You make one call to find the zones. Then you make a few calls for each vendor. 1. `GET /meals/v1/zone/query/documents` finds the zones that serve the place. A zone is a delivery area of one vendor. It covers a city, a province or a whole country. You get the best zone of each vendor that delivers there. 2. `GET /meals/v1/vendor/{vendor_id}/get/document` gives the name of the vendor and its minimum order. 3. `GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documents` lists the dates the zone delivers on. 4. `GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{date}/get/document` says which products you can order for one date. It gives product ids only. 5. `GET /meals/v1/vendor/{vendor_id}/product/query/documents` lists the products of the vendor with their names and prices. One call gives up to 50 products. This is fewer calls than reading each product on its own. That is four calls for each vendor, plus one for the zones. ## 1. Format money Prices are whole numbers of cents. A price of `1299` is 12.99. The currency is the `zone_currency` of the zone you order in. A product or a vendor has no currency of its own. The function `money` turns cents and a currency into text. ```python def money(cents, currency): return f"{cents / 100:.2f} {currency}" ``` ```javascript function money(cents, currency) { return `${(cents / 100).toFixed(2)} ${currency}`; } ``` ```typescript function money(cents: number, currency: string): string { return `${(cents / 100).toFixed(2)} ${currency}`; } ``` ```java static String money(long cents, String currency) { return "%d.%02d %s".formatted(cents / 100, cents % 100, currency); } ``` ## 2. Read the vendor The zone answer holds the id of the vendor. The name is on the vendor. The vendor also has a minimum order: the smallest order value it takes, in cents. An order below it is refused with `order_limits_not_met`. The field is optional, so the code checks for it. ```python def print_vendor(vendor_id, currency): vendor = call("GET", f"/meals/v1/vendor/{vendor_id}/get/document") print() print(vendor["vendor_name"]) minimum = vendor.get("vendor_minimum_order_value") if minimum is not None: print(f" Minimum order: {money(minimum, currency)}") ``` ```javascript async function printVendor(vendorId, currency) { const vendor = await call( 'GET', `/meals/v1/vendor/${vendorId}/get/document`, ); console.log(); console.log(vendor.vendor_name); const minimum = vendor.vendor_minimum_order_value; if (minimum != null) { console.log(` Minimum order: ${money(minimum, currency)}`); } } ``` ```typescript async function printVendor(vendorId: string, currency: string) { const vendor = await call( 'GET', `/meals/v1/vendor/${vendorId}/get/document`, ); console.log(); console.log(vendor.vendor_name); const minimum = vendor.vendor_minimum_order_value; if (minimum != null) { console.log(` Minimum order: ${money(minimum, currency)}`); } } ``` ```java static void printVendor(String vendorId, String currency) { JsonNode vendor = Nurishd.call("GET", "/meals/v1/vendor/%s/get/document".formatted(vendorId)); System.out.println(); System.out.println(vendor.path("vendor_name").asText()); JsonNode minimum = vendor.path("vendor_minimum_order_value"); if (minimum.isNumber()) { System.out.println(" Minimum order: " + money(minimum.asLong(), currency)); } } ``` ## 3. List the delivery dates A delivery date is a day the zone delivers on. The call needs `from` and `to` as `YYYY-MM-DD`. They can be at most 60 days apart. This program asks for the next 14 days. A date is listed only when the zone delivers on that weekday, ordering for it is still open, a menu is in production and it is not a blackout date. A blackout date is a day the vendor does not deliver. Each value looks like `2026-04-07T04:00:00Z`. It is midnight at the start of the delivery day in the vendor's timezone, written in UTC. The part before the `T` is the delivery day. This `YYYY-MM-DD` date is what the next call needs, and what you send later when you place an order. The code keeps the first ten characters of each value. ```python def delivery_days(zone_path): today = date.today() answer = call( "GET", f"{zone_path}/delivery-date/query/documents", {"from": today.isoformat(), "to": (today + timedelta(days=14)).isoformat()}, ) return [value[:10] for value in answer["valid_delivery_dates"]] ``` ```javascript async function deliveryDays(zonePath) { const today = new Date(); const inTwoWeeks = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000); const answer = await call( 'GET', `${zonePath}/delivery-date/query/documents`, { params: { from: today.toISOString().slice(0, 10), to: inTwoWeeks.toISOString().slice(0, 10), }, }, ); return answer.valid_delivery_dates.map((value) => value.slice(0, 10)); } ``` ```typescript async function deliveryDays(zonePath: string): Promise { const today = new Date(); const inTwoWeeks = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000); const answer = await call( 'GET', `${zonePath}/delivery-date/query/documents`, { params: { from: today.toISOString().slice(0, 10), to: inTwoWeeks.toISOString().slice(0, 10), }, }, ); return answer.valid_delivery_dates.map((value) => value.slice(0, 10)); } ``` ```java static List deliveryDays(String zonePath) { LocalDate today = LocalDate.now(); JsonNode answer = Nurishd.call( "GET", zonePath + "/delivery-date/query/documents", Map.of("from", today.toString(), "to", today.plusDays(14).toString()), null); List days = new ArrayList<>(); for (JsonNode value : answer.path("valid_delivery_dates")) { days.add(value.asText().substring(0, 10)); } return days; } ``` ## 4. Read one date and list its meals The date answer has the `order_cutoff_date`. The cutoff is the last moment you can order for that delivery date, in UTC. It also has `all_unique_product_ids`, the ids of every product you can order for that date. The ids have no names or prices. The product list has them. The code reads the vendor's products page by page with the `pages` helper and prints the ones whose id is in the answer. ```python def print_meals(vendor_id, zone_path, day, currency): offer = call("GET", f"{zone_path}/delivery-date/{day}/get/document") offered = set(offer["all_unique_product_ids"]) print(f" Meals on {day} (order before {offer['order_cutoff_date']}):") for product in pages(f"/meals/v1/vendor/{vendor_id}/product/query/documents"): if product["product_id"] in offered: print(f" {product['product_name']}: {money(product['product_price'], currency)}") ``` ```javascript async function printMeals(vendorId, zonePath, day, currency) { const offer = await call( 'GET', `${zonePath}/delivery-date/${day}/get/document`, ); const offered = new Set(offer.all_unique_product_ids); console.log(` Meals on ${day} (order before ${offer.order_cutoff_date}):`); for await (const product of pages( `/meals/v1/vendor/${vendorId}/product/query/documents`, )) { if (offered.has(product.product_id)) { console.log( ` ${product.product_name}: ${money(product.product_price, currency)}`, ); } } } ``` ```typescript async function printMeals( vendorId: string, zonePath: string, day: string, currency: string, ) { const offer = await call( 'GET', `${zonePath}/delivery-date/${day}/get/document`, ); const offered = new Set(offer.all_unique_product_ids); console.log(` Meals on ${day} (order before ${offer.order_cutoff_date}):`); for await (const product of pages( `/meals/v1/vendor/${vendorId}/product/query/documents`, )) { if (offered.has(product.product_id)) { console.log( ` ${product.product_name}: ${money(product.product_price, currency)}`, ); } } } ``` ```java static void printMeals(String vendorId, String zonePath, String day, String currency) { JsonNode offer = Nurishd.call("GET", zonePath + "/delivery-date/%s/get/document".formatted(day)); Set offered = new HashSet<>(); for (JsonNode id : offer.path("all_unique_product_ids")) { offered.add(id.asText()); } System.out.println(" Meals on " + day + " (order before " + offer.path("order_cutoff_date").asText() + "):"); String productsPath = "/meals/v1/vendor/%s/product/query/documents".formatted(vendorId); for (JsonNode product : Nurishd.pages(productsPath, Map.of())) { if (offered.contains(product.path("product_id").asText())) { System.out.println(" " + product.path("product_name").asText() + ": " + money(product.path("product_price").asLong(), currency)); } } } ``` ## 5. Join the steps for one vendor The function `showVendor` runs steps 2 to 4 for one zone. It prints the first five dates. It uses the date you gave, or the first date when you gave none. It says so when the vendor does not deliver on your date. ```python def show_vendor(zone, wanted_date): vendor_id = zone["vendor"] zone_path = f"/meals/v1/vendor/{vendor_id}/zone/{zone['zone_id']}" currency = zone["zone_currency"] print_vendor(vendor_id, currency) days = delivery_days(zone_path) if not days: print(" No delivery dates in the next 14 days.") return print(" Next delivery dates: " + ", ".join(days[:5])) day = wanted_date or days[0] if day not in days: print(f" Does not deliver on {day}.") return print_meals(vendor_id, zone_path, day, currency) ``` ```javascript async function showVendor(zone, wantedDate) { const vendorId = zone.vendor; const zonePath = `/meals/v1/vendor/${vendorId}/zone/${zone.zone_id}`; const currency = zone.zone_currency; await printVendor(vendorId, currency); const days = await deliveryDays(zonePath); if (days.length === 0) { console.log(' No delivery dates in the next 14 days.'); return; } console.log(' Next delivery dates: ' + days.slice(0, 5).join(', ')); const day = wantedDate ?? days[0]; if (!days.includes(day)) { console.log(` Does not deliver on ${day}.`); return; } await printMeals(vendorId, zonePath, day, currency); } ``` ```typescript async function showVendor(zone: Zone, wantedDate?: string) { const vendorId = zone.vendor; const zonePath = `/meals/v1/vendor/${vendorId}/zone/${zone.zone_id}`; const currency = zone.zone_currency; await printVendor(vendorId, currency); const days = await deliveryDays(zonePath); if (days.length === 0) { console.log(' No delivery dates in the next 14 days.'); return; } console.log(' Next delivery dates: ' + days.slice(0, 5).join(', ')); const day = wantedDate ?? days[0]; if (!days.includes(day)) { console.log(` Does not deliver on ${day}.`); return; } await printMeals(vendorId, zonePath, day, currency); } ``` ```java static void showVendor(JsonNode zone, String wantedDate) { String vendorId = zone.path("vendor").asText(); String zonePath = "/meals/v1/vendor/%s/zone/%s".formatted(vendorId, zone.path("zone_id").asText()); String currency = zone.path("zone_currency").asText(); printVendor(vendorId, currency); List days = deliveryDays(zonePath); if (days.isEmpty()) { System.out.println(" No delivery dates in the next 14 days."); return; } System.out.println(" Next delivery dates: " + String.join(", ", days.subList(0, Math.min(5, days.size())))); String day = wantedDate != null ? wantedDate : days.get(0); if (!days.contains(day)) { System.out.println(" Does not deliver on " + day + "."); return; } printMeals(vendorId, zonePath, day, currency); } ``` ## 6. Find the vendors for a place The `main` function reads the place from the command line, finds the zones and shows each vendor. The code makes the province and the country capital letters for you. It prints a message when no vendor delivers there. In the Production environment you see no vendors until Nurish'd enables them for your company. See [Catalog](/docs/meals/catalog). ```python def main(): if len(sys.argv) < 4: print("Usage: python meals.py CITY PROVINCE COUNTRY [YYYY-MM-DD]") sys.exit(1) city = sys.argv[1] state = sys.argv[2].upper() country = sys.argv[3].upper() wanted_date = sys.argv[4] if len(sys.argv) > 4 else None zones = pages( "/meals/v1/zone/query/documents", {"city": city, "state": state, "country": country}, ) found = False for zone in zones: found = True show_vendor(zone, wanted_date) if not found: print(f"No vendor delivers to {city}, {state}, {country}.") ``` ```javascript async function main() { const [city, state, country, wantedDate] = process.argv.slice(2); if (!city || !state || !country) { console.log('Usage: node meals.js CITY PROVINCE COUNTRY [YYYY-MM-DD]'); process.exit(1); } let found = false; for await (const zone of pages('/meals/v1/zone/query/documents', { city, state: state.toUpperCase(), country: country.toUpperCase(), })) { found = true; await showVendor(zone, wantedDate); } if (!found) { console.log(`No vendor delivers to ${city}, ${state}, ${country}.`); } } ``` ```typescript async function main() { const [city, state, country, wantedDate] = process.argv.slice(2); if (!city || !state || !country) { console.log('Usage: node meals.ts CITY PROVINCE COUNTRY [YYYY-MM-DD]'); process.exit(1); } let found = false; for await (const zone of pages('/meals/v1/zone/query/documents', { city, state: state.toUpperCase(), country: country.toUpperCase(), })) { found = true; await showVendor(zone, wantedDate); } if (!found) { console.log(`No vendor delivers to ${city}, ${state}, ${country}.`); } } ``` ```java public static void main(String[] args) { if (args.length < 3) { System.out.println("Pass CITY PROVINCE COUNTRY and an optional YYYY-MM-DD as arguments."); System.exit(1); } String city = args[0]; String state = args[1].toUpperCase(); String country = args[2].toUpperCase(); String wantedDate = args.length > 3 ? args[3] : null; try { List zones = Nurishd.pages( "/meals/v1/zone/query/documents", Map.of("city", city, "state", state, "country", country)); if (zones.isEmpty()) { System.out.println("No vendor delivers to " + city + ", " + state + ", " + country + "."); } for (JsonNode zone : zones) { showVendor(zone, wantedDate); } } catch (NurishdException error) { System.out.println(error.getMessage()); System.exit(1); } } } ``` ## 7. Run it Create the file for your language with the code from the whole program at the end of this page. Run it with a place. | Language | Command | | ---------- | ------------------------------------------------------------------------------------------ | | Python | `python meals.py Mississauga ON CA` | | JavaScript | `node meals.js Mississauga ON CA` | | TypeScript | `node meals.ts Mississauga ON CA` | | Java | `mvn -q compile exec:java -Dexec.mainClass=tutorial.Meals -Dexec.args="Mississauga ON CA"` | Add a date at the end to choose the day. Use a date from the list the program printed. For example `python meals.py Mississauga ON CA 2026-04-10`. You see one block for each vendor. ```text Harbour Kitchen Minimum order: 50.00 CAD Next delivery dates: 2026-04-07, 2026-04-10, 2026-04-14, 2026-04-17 Meals on 2026-04-07 (order before 2026-04-04T19:30:00Z): Salmon Bowl: 14.95 CAD ``` Your dates and meals depend on the vendors and the day you run it. ## Turn it into a page of your site Do not call the catalog from the browser. The browser would need your key. Add a route to your own server instead, such as `GET /meals?city=Mississauga&state=ON&country=CA`. It runs the same calls and returns the result as JSON. Your page reads that JSON. The catalog changes slowly. Keep each answer in memory for a few minutes and serve it again to the next visitor. Each vendor costs four calls, and the Sandbox allows 25 calls a minute by default. See [Rate limits](/docs/concepts/rate-limits). ## The whole program ```python # file: meals.py import sys from datetime import date, timedelta from nurishd import NurishdError, call, pages def money(cents, currency): return f"{cents / 100:.2f} {currency}" def print_vendor(vendor_id, currency): vendor = call("GET", f"/meals/v1/vendor/{vendor_id}/get/document") print() print(vendor["vendor_name"]) minimum = vendor.get("vendor_minimum_order_value") if minimum is not None: print(f" Minimum order: {money(minimum, currency)}") def delivery_days(zone_path): today = date.today() answer = call( "GET", f"{zone_path}/delivery-date/query/documents", {"from": today.isoformat(), "to": (today + timedelta(days=14)).isoformat()}, ) return [value[:10] for value in answer["valid_delivery_dates"]] def print_meals(vendor_id, zone_path, day, currency): offer = call("GET", f"{zone_path}/delivery-date/{day}/get/document") offered = set(offer["all_unique_product_ids"]) print(f" Meals on {day} (order before {offer['order_cutoff_date']}):") for product in pages(f"/meals/v1/vendor/{vendor_id}/product/query/documents"): if product["product_id"] in offered: print(f" {product['product_name']}: {money(product['product_price'], currency)}") def show_vendor(zone, wanted_date): vendor_id = zone["vendor"] zone_path = f"/meals/v1/vendor/{vendor_id}/zone/{zone['zone_id']}" currency = zone["zone_currency"] print_vendor(vendor_id, currency) days = delivery_days(zone_path) if not days: print(" No delivery dates in the next 14 days.") return print(" Next delivery dates: " + ", ".join(days[:5])) day = wanted_date or days[0] if day not in days: print(f" Does not deliver on {day}.") return print_meals(vendor_id, zone_path, day, currency) def main(): if len(sys.argv) < 4: print("Usage: python meals.py CITY PROVINCE COUNTRY [YYYY-MM-DD]") sys.exit(1) city = sys.argv[1] state = sys.argv[2].upper() country = sys.argv[3].upper() wanted_date = sys.argv[4] if len(sys.argv) > 4 else None zones = pages( "/meals/v1/zone/query/documents", {"city": city, "state": state, "country": country}, ) found = False for zone in zones: found = True show_vendor(zone, wanted_date) if not found: print(f"No vendor delivers to {city}, {state}, {country}.") try: main() except NurishdError as error: print(error) sys.exit(1) ``` ```javascript // file: meals.js import { NurishdError, call, pages } from './nurishd.js'; function money(cents, currency) { return `${(cents / 100).toFixed(2)} ${currency}`; } async function printVendor(vendorId, currency) { const vendor = await call( 'GET', `/meals/v1/vendor/${vendorId}/get/document`, ); console.log(); console.log(vendor.vendor_name); const minimum = vendor.vendor_minimum_order_value; if (minimum != null) { console.log(` Minimum order: ${money(minimum, currency)}`); } } async function deliveryDays(zonePath) { const today = new Date(); const inTwoWeeks = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000); const answer = await call( 'GET', `${zonePath}/delivery-date/query/documents`, { params: { from: today.toISOString().slice(0, 10), to: inTwoWeeks.toISOString().slice(0, 10), }, }, ); return answer.valid_delivery_dates.map((value) => value.slice(0, 10)); } async function printMeals(vendorId, zonePath, day, currency) { const offer = await call( 'GET', `${zonePath}/delivery-date/${day}/get/document`, ); const offered = new Set(offer.all_unique_product_ids); console.log(` Meals on ${day} (order before ${offer.order_cutoff_date}):`); for await (const product of pages( `/meals/v1/vendor/${vendorId}/product/query/documents`, )) { if (offered.has(product.product_id)) { console.log( ` ${product.product_name}: ${money(product.product_price, currency)}`, ); } } } async function showVendor(zone, wantedDate) { const vendorId = zone.vendor; const zonePath = `/meals/v1/vendor/${vendorId}/zone/${zone.zone_id}`; const currency = zone.zone_currency; await printVendor(vendorId, currency); const days = await deliveryDays(zonePath); if (days.length === 0) { console.log(' No delivery dates in the next 14 days.'); return; } console.log(' Next delivery dates: ' + days.slice(0, 5).join(', ')); const day = wantedDate ?? days[0]; if (!days.includes(day)) { console.log(` Does not deliver on ${day}.`); return; } await printMeals(vendorId, zonePath, day, currency); } async function main() { const [city, state, country, wantedDate] = process.argv.slice(2); if (!city || !state || !country) { console.log('Usage: node meals.js CITY PROVINCE COUNTRY [YYYY-MM-DD]'); process.exit(1); } let found = false; for await (const zone of pages('/meals/v1/zone/query/documents', { city, state: state.toUpperCase(), country: country.toUpperCase(), })) { found = true; await showVendor(zone, wantedDate); } if (!found) { console.log(`No vendor delivers to ${city}, ${state}, ${country}.`); } } try { await main(); } catch (error) { if (!(error instanceof NurishdError)) throw error; console.log(error.message); process.exit(1); } ``` ```typescript // file: meals.ts import { NurishdError, call, pages } from './nurishd.ts'; interface Zone { zone_id: string; vendor: string; zone_currency: string; } interface Vendor { vendor_name: string; vendor_minimum_order_value?: number | null; } interface DeliveryDates { valid_delivery_dates: string[]; } interface DayOffer { order_cutoff_date: string | null; all_unique_product_ids: string[]; } interface Product { product_id: string; product_name: string; product_price: number; } function money(cents: number, currency: string): string { return `${(cents / 100).toFixed(2)} ${currency}`; } async function printVendor(vendorId: string, currency: string) { const vendor = await call( 'GET', `/meals/v1/vendor/${vendorId}/get/document`, ); console.log(); console.log(vendor.vendor_name); const minimum = vendor.vendor_minimum_order_value; if (minimum != null) { console.log(` Minimum order: ${money(minimum, currency)}`); } } async function deliveryDays(zonePath: string): Promise { const today = new Date(); const inTwoWeeks = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000); const answer = await call( 'GET', `${zonePath}/delivery-date/query/documents`, { params: { from: today.toISOString().slice(0, 10), to: inTwoWeeks.toISOString().slice(0, 10), }, }, ); return answer.valid_delivery_dates.map((value) => value.slice(0, 10)); } async function printMeals( vendorId: string, zonePath: string, day: string, currency: string, ) { const offer = await call( 'GET', `${zonePath}/delivery-date/${day}/get/document`, ); const offered = new Set(offer.all_unique_product_ids); console.log(` Meals on ${day} (order before ${offer.order_cutoff_date}):`); for await (const product of pages( `/meals/v1/vendor/${vendorId}/product/query/documents`, )) { if (offered.has(product.product_id)) { console.log( ` ${product.product_name}: ${money(product.product_price, currency)}`, ); } } } async function showVendor(zone: Zone, wantedDate?: string) { const vendorId = zone.vendor; const zonePath = `/meals/v1/vendor/${vendorId}/zone/${zone.zone_id}`; const currency = zone.zone_currency; await printVendor(vendorId, currency); const days = await deliveryDays(zonePath); if (days.length === 0) { console.log(' No delivery dates in the next 14 days.'); return; } console.log(' Next delivery dates: ' + days.slice(0, 5).join(', ')); const day = wantedDate ?? days[0]; if (!days.includes(day)) { console.log(` Does not deliver on ${day}.`); return; } await printMeals(vendorId, zonePath, day, currency); } async function main() { const [city, state, country, wantedDate] = process.argv.slice(2); if (!city || !state || !country) { console.log('Usage: node meals.ts CITY PROVINCE COUNTRY [YYYY-MM-DD]'); process.exit(1); } let found = false; for await (const zone of pages('/meals/v1/zone/query/documents', { city, state: state.toUpperCase(), country: country.toUpperCase(), })) { found = true; await showVendor(zone, wantedDate); } if (!found) { console.log(`No vendor delivers to ${city}, ${state}, ${country}.`); } } try { await main(); } catch (error) { if (!(error instanceof NurishdError)) throw error; console.log(error.message); process.exit(1); } ``` ```java // file: src/main/java/tutorial/Meals.java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import tutorial.Nurishd.NurishdException; public class Meals { static String money(long cents, String currency) { return "%d.%02d %s".formatted(cents / 100, cents % 100, currency); } static void printVendor(String vendorId, String currency) { JsonNode vendor = Nurishd.call("GET", "/meals/v1/vendor/%s/get/document".formatted(vendorId)); System.out.println(); System.out.println(vendor.path("vendor_name").asText()); JsonNode minimum = vendor.path("vendor_minimum_order_value"); if (minimum.isNumber()) { System.out.println(" Minimum order: " + money(minimum.asLong(), currency)); } } static List deliveryDays(String zonePath) { LocalDate today = LocalDate.now(); JsonNode answer = Nurishd.call( "GET", zonePath + "/delivery-date/query/documents", Map.of("from", today.toString(), "to", today.plusDays(14).toString()), null); List days = new ArrayList<>(); for (JsonNode value : answer.path("valid_delivery_dates")) { days.add(value.asText().substring(0, 10)); } return days; } static void printMeals(String vendorId, String zonePath, String day, String currency) { JsonNode offer = Nurishd.call("GET", zonePath + "/delivery-date/%s/get/document".formatted(day)); Set offered = new HashSet<>(); for (JsonNode id : offer.path("all_unique_product_ids")) { offered.add(id.asText()); } System.out.println(" Meals on " + day + " (order before " + offer.path("order_cutoff_date").asText() + "):"); String productsPath = "/meals/v1/vendor/%s/product/query/documents".formatted(vendorId); for (JsonNode product : Nurishd.pages(productsPath, Map.of())) { if (offered.contains(product.path("product_id").asText())) { System.out.println(" " + product.path("product_name").asText() + ": " + money(product.path("product_price").asLong(), currency)); } } } static void showVendor(JsonNode zone, String wantedDate) { String vendorId = zone.path("vendor").asText(); String zonePath = "/meals/v1/vendor/%s/zone/%s".formatted(vendorId, zone.path("zone_id").asText()); String currency = zone.path("zone_currency").asText(); printVendor(vendorId, currency); List days = deliveryDays(zonePath); if (days.isEmpty()) { System.out.println(" No delivery dates in the next 14 days."); return; } System.out.println(" Next delivery dates: " + String.join(", ", days.subList(0, Math.min(5, days.size())))); String day = wantedDate != null ? wantedDate : days.get(0); if (!days.contains(day)) { System.out.println(" Does not deliver on " + day + "."); return; } printMeals(vendorId, zonePath, day, currency); } public static void main(String[] args) { if (args.length < 3) { System.out.println("Pass CITY PROVINCE COUNTRY and an optional YYYY-MM-DD as arguments."); System.exit(1); } String city = args[0]; String state = args[1].toUpperCase(); String country = args[2].toUpperCase(); String wantedDate = args.length > 3 ? args[3] : null; try { List zones = Nurishd.pages( "/meals/v1/zone/query/documents", Map.of("city", city, "state", state, "country", country)); if (zones.isEmpty()) { System.out.println("No vendor delivers to " + city + ", " + state + ", " + country + "."); } for (JsonNode zone : zones) { showVendor(zone, wantedDate); } } catch (NurishdException error) { System.out.println(error.getMessage()); System.exit(1); } } } ``` ## If something goes wrong | What you see | Why | What to do | | ------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `No vendor delivers to ...` | No zone matches the place. Letter case counts in the city. | Check the spelling of the city. Try the province or the country the zone covers. | | `403 scope_not_granted` | Your key lacks `catalog:read`. | Create a key with the scope. | | `422 validation_error` | The province or the country is not two letters, or the city has `$`, `{` or `}`. | Use codes such as `ON` and `CA`. | | `404 not_found` on a vendor or a zone | The vendor is not live, or it is not enabled for your company in Production. | Ask Nurish'd to enable the vendor. | | `Does not deliver on ` | The zone does not offer that date. The cutoff has passed, or no menu is ready. | Choose a date from the list. | | `429 rate_limited` | You went over the calls allowed each minute. | The client waits once and tries again. Wait for the minute to pass. | ## Next - [Catalog](/docs/meals/catalog): menus, products and delivery dates in full. - [Pagination](/docs/concepts/pagination): lists and filters. - [Connect a customer from your own sign-in](/docs/tutorials/connect-a-customer): link a customer to your company. - [Place a meal order](/docs/tutorials/place-a-meal-order): order the meals you found. --- # Place a meal order Build a small web app that places a meal order for a connected customer, lets the customer pay with Stripe.js, and reads the order back. You will build a small web app. A page sends a basket to your server. Your server places the order with Nurish'd. The customer pays on the page. Your server reads the order back and says where it stands. ## Before you start - You finished [Set up your project](/docs/tutorials/set-up-your-project). Your project has the `nurishd` client file and a Sandbox key in `NURISHD_API_KEY`. - You have a connected customer. You get one in [Connect a customer from your own sign-in](/docs/tutorials/connect-a-customer). You need the customer's id, which the create call answers as `user`. - You have a vendor, a delivery date and product ids. You get them in [Show meals for an address and a date](/docs/tutorials/show-meals-for-an-address). - Your key has the scopes `order:write` and `order:read`. They are needed to place an order and to read it. Run `check_key` from the setup tutorial to see your scopes. - Install the web server package for your language. | Language | Command | | ---------- | ------------------------------------------------------------------------ | | Python | `pip install flask` | | JavaScript | `npm install express` | | TypeScript | `npm install express` and `npm install --save-dev @types/express` | | Java | Replace `pom.xml` with the one below. It adds Javalin and a log package. | ## How an order is paid You do not take the card on your server. The order answer carries what your page needs to take the payment: - `stripe_payment_intent.stripe_payment_intent_client_secret` is a secret for this one payment. A payment intent is Stripe's record of a payment that is being made. - `stripe_publishable_key` is the Stripe key your page uses. It is safe to put in a page. Your page uses [Stripe.js](https://docs.stripe.com/js), Stripe's library for the browser. The customer types the card into Stripe's own form. The card number never reaches your server or Nurish'd. A customer who saved a card can pay without typing it again. See [Saving a card](/docs/meals/saving-a-card). ## 1. Set up the server The server has two routes: `POST /orders` and `GET /orders/`. It also serves the page `public/pay.html`, which you write in step 3. `REQUIRED` lists the fields of a basket. `ORDER_ID` checks the shape of an order id, because the id goes into a URL path. `refusal` sends the browser the code and the message of an error from Nurish'd. ```python # Flask serves the files in public/ at the site root, so public/pay.html is /pay.html. app = Flask(__name__, static_folder="public", static_url_path="") REQUIRED = ["customer_id", "vendor_id", "delivery_date", "items", "address", "email", "phone", "reference"] # An order id goes into a URL path, so check its shape before you use it. ORDER_ID = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}") def refusal(error): return jsonify(code=error.code, message=str(error)), error.status ``` ```javascript const app = express(); app.use(express.json()); // Express serves the files in public/ at the site root, so public/pay.html is /pay.html. app.use(express.static('public')); const REQUIRED = [ 'customer_id', 'vendor_id', 'delivery_date', 'items', 'address', 'email', 'phone', 'reference', ]; // An order id goes into a URL path, so check its shape before you use it. const ORDER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/; function refusal(res, error) { res.status(error.status).json({ code: error.code, message: error.message }); } ``` ```typescript interface Basket { customer_id: string; vendor_id: string; delivery_date: string; items: { product_id: string; quantity: number }[]; address: Record; email: string; phone: string; reference: string; } interface Order { order_id: string; order_financial_status: string; order_fulfillment_status: string; order_delivery_status: string; order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING: number; order_currency: string; stripe_payment_intent: { stripe_payment_intent_client_secret: string; } | null; stripe_publishable_key: string | null; } const app = express(); app.use(express.json()); // Express serves the files in public/ at the site root, so public/pay.html is /pay.html. app.use(express.static('public')); const REQUIRED = [ 'customer_id', 'vendor_id', 'delivery_date', 'items', 'address', 'email', 'phone', 'reference', ]; // An order id goes into a URL path, so check its shape before you use it. const ORDER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/; function refusal(res: Response, error: NurishdError) { res.status(error.status).json({ code: error.code, message: error.message }); } ``` ```java static final List REQUIRED = List.of("customer_id", "vendor_id", "delivery_date", "items", "address", "email", "phone", "reference"); // An order id goes into a URL path, so check its shape before you use it. static final Pattern ORDER_ID = Pattern.compile("[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}"); static void fail(Context ctx, int status, String code, String message) { ObjectNode body = Nurishd.JSON.createObjectNode(); body.put("code", code); body.put("message", message); ctx.status(status).json(body); } ``` ## 2. Place the order `POST /orders` takes a basket and calls `POST /meals/v1/order/create/document`. The basket has these fields. | Basket field | Becomes | What it is | | --------------- | ------------------------ | --------------------------------------------------- | | `customer_id` | `user` | The id of the connected customer. | | `vendor_id` | `order_vendor` | The id of the vendor. | | `delivery_date` | `order_delivery_date` | A day the zone offers, as `YYYY-MM-DD`. | | `items` | `line_items` | Product ids and quantities. | | `address` | `order_shipping_address` | Where to deliver, with the limits in step 5. | | `email` | `order_contact_email` | How the kitchen and the courier reach the customer. | | `phone` | `order_contact_phone` | The phone number with its country code. | | `reference` | `reference` | Your own order number. | The `reference` makes a retry safe. If you send the same `reference` again, Nurish'd returns the order it already placed and does not place a second one. When a call times out, send it again with the same `reference`. The customer's id comes from the page in this tutorial, to keep it short. In a real app the server takes it from the signed-in session. Never let a browser choose whose orders it places. The answer holds the whole order. The route sends the browser only three things: the order id, the client secret and the publishable key. An order that costs nothing is paid at once, and its `stripe_payment_intent` is `null`. Never log the client secret. ```python @app.post("/orders") def place_order(): basket = request.get_json() missing = [name for name in REQUIRED if name not in basket] if missing: return jsonify(code="bad_basket", message="Missing: " + ", ".join(missing)), 400 try: order = call( "POST", "/meals/v1/order/create/document", body={ "user": basket["customer_id"], "order_vendor": basket["vendor_id"], "order_delivery_date": basket["delivery_date"], "line_items": [ { "line_item_product_id": item["product_id"], "line_quantity": item["quantity"], } for item in basket["items"] ], "order_shipping_address": basket["address"], "order_contact_email": basket["email"], "order_contact_phone": basket["phone"], "reference": basket["reference"], }, ) except NurishdError as error: return refusal(error) # Send the browser only what it needs to pay. intent = order["stripe_payment_intent"] return ( jsonify( order_id=order["order_id"], client_secret=intent["stripe_payment_intent_client_secret"] if intent else None, publishable_key=order["stripe_publishable_key"], ), 201, ) ``` ```javascript app.post('/orders', async (req, res) => { const basket = req.body; const missing = REQUIRED.filter((name) => !(name in basket)); if (missing.length > 0) { return res.status(400).json({ code: 'bad_basket', message: 'Missing: ' + missing.join(', '), }); } let order; try { order = await call('POST', '/meals/v1/order/create/document', { body: { user: basket.customer_id, order_vendor: basket.vendor_id, order_delivery_date: basket.delivery_date, line_items: basket.items.map((item) => ({ line_item_product_id: item.product_id, line_quantity: item.quantity, })), order_shipping_address: basket.address, order_contact_email: basket.email, order_contact_phone: basket.phone, reference: basket.reference, }, }); } catch (error) { if (!(error instanceof NurishdError)) throw error; return refusal(res, error); } // Send the browser only what it needs to pay. res.status(201).json({ order_id: order.order_id, client_secret: order.stripe_payment_intent?.stripe_payment_intent_client_secret ?? null, publishable_key: order.stripe_publishable_key, }); }); ``` ```typescript app.post('/orders', async (req, res) => { const basket = req.body as Basket; const missing = REQUIRED.filter((name) => !(name in basket)); if (missing.length > 0) { return res.status(400).json({ code: 'bad_basket', message: 'Missing: ' + missing.join(', '), }); } let order: Order; try { order = await call('POST', '/meals/v1/order/create/document', { body: { user: basket.customer_id, order_vendor: basket.vendor_id, order_delivery_date: basket.delivery_date, line_items: basket.items.map((item) => ({ line_item_product_id: item.product_id, line_quantity: item.quantity, })), order_shipping_address: basket.address, order_contact_email: basket.email, order_contact_phone: basket.phone, reference: basket.reference, }, }); } catch (error) { if (!(error instanceof NurishdError)) throw error; return refusal(res, error); } // Send the browser only what it needs to pay. res.status(201).json({ order_id: order.order_id, client_secret: order.stripe_payment_intent?.stripe_payment_intent_client_secret ?? null, publishable_key: order.stripe_publishable_key, }); }); ``` ```java static void placeOrder(Context ctx) throws Exception { JsonNode basket = Nurishd.JSON.readTree(ctx.body()); List missing = new ArrayList<>(); for (String name : REQUIRED) { if (!basket.has(name)) missing.add(name); } if (!missing.isEmpty()) { fail(ctx, 400, "bad_basket", "Missing: " + String.join(", ", missing)); return; } ObjectNode body = Nurishd.JSON.createObjectNode(); body.put("user", basket.path("customer_id").asText()); body.put("order_vendor", basket.path("vendor_id").asText()); body.put("order_delivery_date", basket.path("delivery_date").asText()); ArrayNode lineItems = body.putArray("line_items"); for (JsonNode item : basket.path("items")) { ObjectNode line = lineItems.addObject(); line.put("line_item_product_id", item.path("product_id").asText()); line.put("line_quantity", item.path("quantity").asInt()); } body.set("order_shipping_address", basket.path("address")); body.put("order_contact_email", basket.path("email").asText()); body.put("order_contact_phone", basket.path("phone").asText()); body.put("reference", basket.path("reference").asText()); JsonNode order; try { order = Nurishd.call("POST", "/meals/v1/order/create/document", Map.of(), body); } catch (NurishdException error) { fail(ctx, error.status, error.code, error.getMessage()); return; } // Send the browser only what it needs to pay. ObjectNode answer = Nurishd.JSON.createObjectNode(); answer.put("order_id", order.path("order_id").asText()); JsonNode secret = order.path("stripe_payment_intent").path("stripe_payment_intent_client_secret"); answer.set("client_secret", secret.isMissingNode() ? Nurishd.JSON.nullNode() : secret); answer.set("publishable_key", order.path("stripe_publishable_key")); ctx.status(201).json(answer); } ``` ## 3. Add the payment page The page lets you edit a basket and press **Place order**. It calls your route, then shows Stripe's card form and confirms the payment with `stripe.confirmCardPayment`. This code runs in the browser, never on your server. Create a folder named `public` next to your program. Create `public/pay.html` in it. Change the basket to your customer, vendor, date and products. Change `reference` for every new order. The same `reference` returns the first order. ```html Place a meal order

Place a meal order

Edit the basket, then press Place order.

``` The page does not tell you that the order is paid. Stripe says the card was accepted. Only the order says that it is paid. See step 4. The publishable key shows which Stripe mode the form uses. A key that starts with `pk_test_` takes Stripe's test cards. See [Stripe's testing guide](https://docs.stripe.com/testing). ## 4. Read the order `GET /orders/` calls `GET /meals/v1/order/{order_id}/get/document`. The answer has the order's three statuses. The route sends them on, with one sentence in plain words that `say` picks. An order is confirmed when it is paid. Do not treat it as paid because your page says the card was accepted. The order is paid when `order_financial_status` is `paid`. Read the order again to see its present state. If the customer reloads before paying, this read returns the client secret again while the payment is `pending`. The three statuses mean this for your customer. | Field | Value | What it means for your customer | | -------------------------- | ----------------- | ------------------------------------------------- | | `order_financial_status` | `pending` | The order waits for the payment. | | `order_financial_status` | `paid` | The payment went through. The order is confirmed. | | `order_financial_status` | `failed payment` | The payment did not go through. | | `order_financial_status` | `refunded` | The money went back to the customer. | | `order_financial_status` | `cancelled` | The order was cancelled. | | `order_fulfillment_status` | `pending payment` | The kitchen waits for the payment. | | `order_fulfillment_status` | `not started` | The kitchen has not started yet. | | `order_fulfillment_status` | `preparing meals` | The kitchen is cooking the meals. | | `order_fulfillment_status` | `completed` | The meals are ready. | | `order_delivery_status` | `pending payment` | Nothing ships before the payment. | | `order_delivery_status` | `not yet shipped` | The order waits for the courier. | | `order_delivery_status` | `shipped` | The order is on its way. | | `order_delivery_status` | `delivered` | The order arrived. | | `order_delivery_status` | `delivery failed` | The courier could not deliver it. | The contract lists more values, such as `partially refunded`, `chargeback` and `do not process`. The last lines of the file start the server. ```python def say(order): payment = order["order_financial_status"] delivery = order["order_delivery_status"] if payment == "pending": return "Waiting for payment." if payment == "failed payment": return "The payment failed." if payment == "paid": if delivery == "delivered": return "Delivered." if delivery == "shipped": return "On its way." return "Paid. The kitchen is getting it ready." return f"Payment status: {payment}." @app.get("/orders/") def read_order(order_id): if not ORDER_ID.fullmatch(order_id): return jsonify(code="bad_order_id", message="This order id is not valid."), 400 try: order = call("GET", f"/meals/v1/order/{order_id}/get/document") except NurishdError as error: return refusal(error) return jsonify( order_id=order["order_id"], summary=say(order), payment=order["order_financial_status"], kitchen=order["order_fulfillment_status"], delivery=order["order_delivery_status"], total_cents=order["order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING"], currency=order["order_currency"], ) app.run(port=3000) ``` ```javascript function say(order) { const payment = order.order_financial_status; const delivery = order.order_delivery_status; if (payment === 'pending') return 'Waiting for payment.'; if (payment === 'failed payment') return 'The payment failed.'; if (payment === 'paid') { if (delivery === 'delivered') return 'Delivered.'; if (delivery === 'shipped') return 'On its way.'; return 'Paid. The kitchen is getting it ready.'; } return `Payment status: ${payment}.`; } app.get('/orders/:orderId', async (req, res) => { const orderId = req.params.orderId; if (!ORDER_ID.test(orderId)) { return res.status(400).json({ code: 'bad_order_id', message: 'This order id is not valid.', }); } let order; try { order = await call('GET', `/meals/v1/order/${orderId}/get/document`); } catch (error) { if (!(error instanceof NurishdError)) throw error; return refusal(res, error); } res.json({ order_id: order.order_id, summary: say(order), payment: order.order_financial_status, kitchen: order.order_fulfillment_status, delivery: order.order_delivery_status, total_cents: order.order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING, currency: order.order_currency, }); }); app.listen(3000, () => console.log('Listening on http://localhost:3000')); ``` ```typescript function say(order: Order): string { const payment = order.order_financial_status; const delivery = order.order_delivery_status; if (payment === 'pending') return 'Waiting for payment.'; if (payment === 'failed payment') return 'The payment failed.'; if (payment === 'paid') { if (delivery === 'delivered') return 'Delivered.'; if (delivery === 'shipped') return 'On its way.'; return 'Paid. The kitchen is getting it ready.'; } return `Payment status: ${payment}.`; } app.get('/orders/:orderId', async (req, res) => { const orderId = req.params.orderId; if (!ORDER_ID.test(orderId)) { return res.status(400).json({ code: 'bad_order_id', message: 'This order id is not valid.', }); } let order: Order; try { order = await call( 'GET', `/meals/v1/order/${orderId}/get/document`, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; return refusal(res, error); } res.json({ order_id: order.order_id, summary: say(order), payment: order.order_financial_status, kitchen: order.order_fulfillment_status, delivery: order.order_delivery_status, total_cents: order.order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING, currency: order.order_currency, }); }); app.listen(3000, () => console.log('Listening on http://localhost:3000')); ``` ```java static String say(JsonNode order) { String payment = order.path("order_financial_status").asText(); String delivery = order.path("order_delivery_status").asText(); if (payment.equals("pending")) return "Waiting for payment."; if (payment.equals("failed payment")) return "The payment failed."; if (payment.equals("paid")) { if (delivery.equals("delivered")) return "Delivered."; if (delivery.equals("shipped")) return "On its way."; return "Paid. The kitchen is getting it ready."; } return "Payment status: " + payment + "."; } static void readOrder(Context ctx) { String orderId = ctx.pathParam("orderId"); if (!ORDER_ID.matcher(orderId).matches()) { fail(ctx, 400, "bad_order_id", "This order id is not valid."); return; } JsonNode order; try { order = Nurishd.call("GET", "/meals/v1/order/%s/get/document".formatted(orderId)); } catch (NurishdException error) { fail(ctx, error.status, error.code, error.getMessage()); return; } ObjectNode answer = Nurishd.JSON.createObjectNode(); answer.put("order_id", order.path("order_id").asText()); answer.put("summary", say(order)); answer.set("payment", order.path("order_financial_status")); answer.set("kitchen", order.path("order_fulfillment_status")); answer.set("delivery", order.path("order_delivery_status")); answer.set("total_cents", order.path("order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING")); answer.set("currency", order.path("order_currency")); ctx.json(answer); } public static void main(String[] args) { // Javalin serves the files in public/ at the site root, so public/pay.html is /pay.html. Javalin app = Javalin.create(config -> config.staticFiles.add("public", Location.EXTERNAL)); app.post("/orders", Orders::placeOrder); app.get("/orders/{orderId}", Orders::readOrder); app.start(3000); } } ``` ## 5. Know the rules that refuse an order Nurish'd checks the order before it places anything. A refusal creates nothing. Check these on your side too, so the customer sees a clear message before the call. | What you send | The rule | | -------------------------------- | ----------------------------------------------------------------------------------------------- | | `delivery_date` | `YYYY-MM-DD`, the date part of a delivery date the zone offers. No time of day. | | `items` | 1 to 50 items. Each has a product id and a quantity of at least 1. A product appears only once. | | Each product | It must be offered on that date. See [Catalog](/docs/meals/catalog). | | The order as a whole | It must meet the vendor's limits on items and value, such as the minimum order. | | `address.line1`, `line2`, `city` | Up to 200, 200 and 100 characters. `$`, `{` and `}` are not accepted. | | `address.state`, `country` | Two capital letters, such as `ON` and `CA`. | | `address.postal_code` | Letters, digits, spaces and hyphens, up to 20 characters. | | `phone` | The country code first, such as `+14165550123`. At most 20 characters. | The customer's connection must be `active` and must allow orders. ## 6. Run it Create the program file for your language and `public/pay.html`. Start the server. | Language | Command | | ---------- | ----------------------------------------------------------- | | Python | `python orders.py` | | JavaScript | `node orders.js` | | TypeScript | `node orders.ts` | | Java | `mvn -q compile exec:java -Dexec.mainClass=tutorial.Orders` | Post a basket with `curl`. Use the ids of your own customer, vendor and products. ```bash curl -X POST http://localhost:3000/orders \ -H "Content-Type: application/json" \ -d '{ "customer_id": "6f1c0d2e-0000-4000-8000-000000000101", "vendor_id": "vendor-harbour-kitchen", "delivery_date": "2026-04-07", "items": [ { "product_id": "product-salmon-bowl", "quantity": 4 }, { "product_id": "product-chicken-wrap", "quantity": 2 } ], "address": { "line1": "10 Example Street", "city": "Toronto", "state": "ON", "postal_code": "M5V 2T6", "country": "CA" }, "email": "ada.lovelace@example.com", "phone": "+14165550123", "reference": "web-order-1001" }' ``` The answer has the three things the page needs. Your values differ. ```text {"order_id":"ORD-ONE-OFF-4F7K2A9Q","client_secret":"pi_3QExample0001_secret_a1B2c3D4e5F6g7H8i9J0","publishable_key":"pk_test_51QExample0001abcdefghijklmnop"} ``` Read the order back with the `order_id` of the answer. ```bash curl http://localhost:3000/orders/ORD-ONE-OFF-4F7K2A9Q ``` ```text {"order_id":"ORD-ONE-OFF-4F7K2A9Q","summary":"Waiting for payment.","payment":"pending","kitchen":"pending payment","delivery":"pending payment","total_cents":7874,"currency":"CAD"} ``` The order waits for its payment. After the customer pays, the payment status changes to `paid`. To pay, open `http://localhost:3000/pay.html` in a browser, press **Place order**, enter a card in the form and press **Pay**. Then read the order again. The page says the card was accepted. The order is paid when its payment status is `paid`. ## When the order is confirmed The order is confirmed when it is paid. Your page cannot tell you that, and a customer may close the tab before the order changes. Nurish'd sends an `order.paid` event to your server when the payment is done. Use it to update your records. See [Receive order webhooks](/docs/tutorials/receive-order-webhooks). ## The whole program ```python # file: orders.py import re from flask import Flask, jsonify, request from nurishd import NurishdError, call # Flask serves the files in public/ at the site root, so public/pay.html is /pay.html. app = Flask(__name__, static_folder="public", static_url_path="") REQUIRED = ["customer_id", "vendor_id", "delivery_date", "items", "address", "email", "phone", "reference"] # An order id goes into a URL path, so check its shape before you use it. ORDER_ID = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}") def refusal(error): return jsonify(code=error.code, message=str(error)), error.status @app.post("/orders") def place_order(): basket = request.get_json() missing = [name for name in REQUIRED if name not in basket] if missing: return jsonify(code="bad_basket", message="Missing: " + ", ".join(missing)), 400 try: order = call( "POST", "/meals/v1/order/create/document", body={ "user": basket["customer_id"], "order_vendor": basket["vendor_id"], "order_delivery_date": basket["delivery_date"], "line_items": [ { "line_item_product_id": item["product_id"], "line_quantity": item["quantity"], } for item in basket["items"] ], "order_shipping_address": basket["address"], "order_contact_email": basket["email"], "order_contact_phone": basket["phone"], "reference": basket["reference"], }, ) except NurishdError as error: return refusal(error) # Send the browser only what it needs to pay. intent = order["stripe_payment_intent"] return ( jsonify( order_id=order["order_id"], client_secret=intent["stripe_payment_intent_client_secret"] if intent else None, publishable_key=order["stripe_publishable_key"], ), 201, ) def say(order): payment = order["order_financial_status"] delivery = order["order_delivery_status"] if payment == "pending": return "Waiting for payment." if payment == "failed payment": return "The payment failed." if payment == "paid": if delivery == "delivered": return "Delivered." if delivery == "shipped": return "On its way." return "Paid. The kitchen is getting it ready." return f"Payment status: {payment}." @app.get("/orders/") def read_order(order_id): if not ORDER_ID.fullmatch(order_id): return jsonify(code="bad_order_id", message="This order id is not valid."), 400 try: order = call("GET", f"/meals/v1/order/{order_id}/get/document") except NurishdError as error: return refusal(error) return jsonify( order_id=order["order_id"], summary=say(order), payment=order["order_financial_status"], kitchen=order["order_fulfillment_status"], delivery=order["order_delivery_status"], total_cents=order["order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING"], currency=order["order_currency"], ) app.run(port=3000) ``` ```javascript // file: orders.js import express from 'express'; import { NurishdError, call } from './nurishd.js'; const app = express(); app.use(express.json()); // Express serves the files in public/ at the site root, so public/pay.html is /pay.html. app.use(express.static('public')); const REQUIRED = [ 'customer_id', 'vendor_id', 'delivery_date', 'items', 'address', 'email', 'phone', 'reference', ]; // An order id goes into a URL path, so check its shape before you use it. const ORDER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/; function refusal(res, error) { res.status(error.status).json({ code: error.code, message: error.message }); } app.post('/orders', async (req, res) => { const basket = req.body; const missing = REQUIRED.filter((name) => !(name in basket)); if (missing.length > 0) { return res.status(400).json({ code: 'bad_basket', message: 'Missing: ' + missing.join(', '), }); } let order; try { order = await call('POST', '/meals/v1/order/create/document', { body: { user: basket.customer_id, order_vendor: basket.vendor_id, order_delivery_date: basket.delivery_date, line_items: basket.items.map((item) => ({ line_item_product_id: item.product_id, line_quantity: item.quantity, })), order_shipping_address: basket.address, order_contact_email: basket.email, order_contact_phone: basket.phone, reference: basket.reference, }, }); } catch (error) { if (!(error instanceof NurishdError)) throw error; return refusal(res, error); } // Send the browser only what it needs to pay. res.status(201).json({ order_id: order.order_id, client_secret: order.stripe_payment_intent?.stripe_payment_intent_client_secret ?? null, publishable_key: order.stripe_publishable_key, }); }); function say(order) { const payment = order.order_financial_status; const delivery = order.order_delivery_status; if (payment === 'pending') return 'Waiting for payment.'; if (payment === 'failed payment') return 'The payment failed.'; if (payment === 'paid') { if (delivery === 'delivered') return 'Delivered.'; if (delivery === 'shipped') return 'On its way.'; return 'Paid. The kitchen is getting it ready.'; } return `Payment status: ${payment}.`; } app.get('/orders/:orderId', async (req, res) => { const orderId = req.params.orderId; if (!ORDER_ID.test(orderId)) { return res.status(400).json({ code: 'bad_order_id', message: 'This order id is not valid.', }); } let order; try { order = await call('GET', `/meals/v1/order/${orderId}/get/document`); } catch (error) { if (!(error instanceof NurishdError)) throw error; return refusal(res, error); } res.json({ order_id: order.order_id, summary: say(order), payment: order.order_financial_status, kitchen: order.order_fulfillment_status, delivery: order.order_delivery_status, total_cents: order.order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING, currency: order.order_currency, }); }); app.listen(3000, () => console.log('Listening on http://localhost:3000')); ``` ```typescript // file: orders.ts import express, { type Response } from 'express'; import { NurishdError, call } from './nurishd.ts'; interface Basket { customer_id: string; vendor_id: string; delivery_date: string; items: { product_id: string; quantity: number }[]; address: Record; email: string; phone: string; reference: string; } interface Order { order_id: string; order_financial_status: string; order_fulfillment_status: string; order_delivery_status: string; order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING: number; order_currency: string; stripe_payment_intent: { stripe_payment_intent_client_secret: string; } | null; stripe_publishable_key: string | null; } const app = express(); app.use(express.json()); // Express serves the files in public/ at the site root, so public/pay.html is /pay.html. app.use(express.static('public')); const REQUIRED = [ 'customer_id', 'vendor_id', 'delivery_date', 'items', 'address', 'email', 'phone', 'reference', ]; // An order id goes into a URL path, so check its shape before you use it. const ORDER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/; function refusal(res: Response, error: NurishdError) { res.status(error.status).json({ code: error.code, message: error.message }); } app.post('/orders', async (req, res) => { const basket = req.body as Basket; const missing = REQUIRED.filter((name) => !(name in basket)); if (missing.length > 0) { return res.status(400).json({ code: 'bad_basket', message: 'Missing: ' + missing.join(', '), }); } let order: Order; try { order = await call('POST', '/meals/v1/order/create/document', { body: { user: basket.customer_id, order_vendor: basket.vendor_id, order_delivery_date: basket.delivery_date, line_items: basket.items.map((item) => ({ line_item_product_id: item.product_id, line_quantity: item.quantity, })), order_shipping_address: basket.address, order_contact_email: basket.email, order_contact_phone: basket.phone, reference: basket.reference, }, }); } catch (error) { if (!(error instanceof NurishdError)) throw error; return refusal(res, error); } // Send the browser only what it needs to pay. res.status(201).json({ order_id: order.order_id, client_secret: order.stripe_payment_intent?.stripe_payment_intent_client_secret ?? null, publishable_key: order.stripe_publishable_key, }); }); function say(order: Order): string { const payment = order.order_financial_status; const delivery = order.order_delivery_status; if (payment === 'pending') return 'Waiting for payment.'; if (payment === 'failed payment') return 'The payment failed.'; if (payment === 'paid') { if (delivery === 'delivered') return 'Delivered.'; if (delivery === 'shipped') return 'On its way.'; return 'Paid. The kitchen is getting it ready.'; } return `Payment status: ${payment}.`; } app.get('/orders/:orderId', async (req, res) => { const orderId = req.params.orderId; if (!ORDER_ID.test(orderId)) { return res.status(400).json({ code: 'bad_order_id', message: 'This order id is not valid.', }); } let order: Order; try { order = await call( 'GET', `/meals/v1/order/${orderId}/get/document`, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; return refusal(res, error); } res.json({ order_id: order.order_id, summary: say(order), payment: order.order_financial_status, kitchen: order.order_fulfillment_status, delivery: order.order_delivery_status, total_cents: order.order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING, currency: order.order_currency, }); }); app.listen(3000, () => console.log('Listening on http://localhost:3000')); ``` ```java // file: src/main/java/tutorial/Orders.java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.javalin.Javalin; import io.javalin.http.Context; import io.javalin.http.staticfiles.Location; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import tutorial.Nurishd.NurishdException; public class Orders { static final List REQUIRED = List.of("customer_id", "vendor_id", "delivery_date", "items", "address", "email", "phone", "reference"); // An order id goes into a URL path, so check its shape before you use it. static final Pattern ORDER_ID = Pattern.compile("[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}"); static void fail(Context ctx, int status, String code, String message) { ObjectNode body = Nurishd.JSON.createObjectNode(); body.put("code", code); body.put("message", message); ctx.status(status).json(body); } static void placeOrder(Context ctx) throws Exception { JsonNode basket = Nurishd.JSON.readTree(ctx.body()); List missing = new ArrayList<>(); for (String name : REQUIRED) { if (!basket.has(name)) missing.add(name); } if (!missing.isEmpty()) { fail(ctx, 400, "bad_basket", "Missing: " + String.join(", ", missing)); return; } ObjectNode body = Nurishd.JSON.createObjectNode(); body.put("user", basket.path("customer_id").asText()); body.put("order_vendor", basket.path("vendor_id").asText()); body.put("order_delivery_date", basket.path("delivery_date").asText()); ArrayNode lineItems = body.putArray("line_items"); for (JsonNode item : basket.path("items")) { ObjectNode line = lineItems.addObject(); line.put("line_item_product_id", item.path("product_id").asText()); line.put("line_quantity", item.path("quantity").asInt()); } body.set("order_shipping_address", basket.path("address")); body.put("order_contact_email", basket.path("email").asText()); body.put("order_contact_phone", basket.path("phone").asText()); body.put("reference", basket.path("reference").asText()); JsonNode order; try { order = Nurishd.call("POST", "/meals/v1/order/create/document", Map.of(), body); } catch (NurishdException error) { fail(ctx, error.status, error.code, error.getMessage()); return; } // Send the browser only what it needs to pay. ObjectNode answer = Nurishd.JSON.createObjectNode(); answer.put("order_id", order.path("order_id").asText()); JsonNode secret = order.path("stripe_payment_intent").path("stripe_payment_intent_client_secret"); answer.set("client_secret", secret.isMissingNode() ? Nurishd.JSON.nullNode() : secret); answer.set("publishable_key", order.path("stripe_publishable_key")); ctx.status(201).json(answer); } static String say(JsonNode order) { String payment = order.path("order_financial_status").asText(); String delivery = order.path("order_delivery_status").asText(); if (payment.equals("pending")) return "Waiting for payment."; if (payment.equals("failed payment")) return "The payment failed."; if (payment.equals("paid")) { if (delivery.equals("delivered")) return "Delivered."; if (delivery.equals("shipped")) return "On its way."; return "Paid. The kitchen is getting it ready."; } return "Payment status: " + payment + "."; } static void readOrder(Context ctx) { String orderId = ctx.pathParam("orderId"); if (!ORDER_ID.matcher(orderId).matches()) { fail(ctx, 400, "bad_order_id", "This order id is not valid."); return; } JsonNode order; try { order = Nurishd.call("GET", "/meals/v1/order/%s/get/document".formatted(orderId)); } catch (NurishdException error) { fail(ctx, error.status, error.code, error.getMessage()); return; } ObjectNode answer = Nurishd.JSON.createObjectNode(); answer.put("order_id", order.path("order_id").asText()); answer.put("summary", say(order)); answer.set("payment", order.path("order_financial_status")); answer.set("kitchen", order.path("order_fulfillment_status")); answer.set("delivery", order.path("order_delivery_status")); answer.set("total_cents", order.path("order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING")); answer.set("currency", order.path("order_currency")); ctx.json(answer); } public static void main(String[] args) { // Javalin serves the files in public/ at the site root, so public/pay.html is /pay.html. Javalin app = Javalin.create(config -> config.staticFiles.add("public", Location.EXTERNAL)); app.post("/orders", Orders::placeOrder); app.get("/orders/{orderId}", Orders::readOrder); app.start(3000); } } ``` ```xml 4.0.0 com.example nurishd-tutorial 1.0.0 17 UTF-8 com.fasterxml.jackson.core jackson-databind 2.17.2 io.javalin javalin 6.3.0 org.slf4j slf4j-simple 2.0.16 org.codehaus.mojo exec-maven-plugin 3.4.1 ``` ## If something goes wrong | What you see | Why | What to do | | --------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | `409 connection_not_active` | The customer has not approved, or they revoked the link. | Send the customer through [Connect a customer](/docs/tutorials/connect-a-customer) again. | | `403 connection_scope_not_granted` | The customer did not allow orders. | Ask the customer to approve again. | | `403 scope_not_granted` | Your key lacks `order:write` or `order:read`. | Create a key with both scopes. | | `404 not_found` when you place an order | The customer is unknown, or the vendor cannot be used. | Check the customer id. In Production, ask Nurish'd to enable the vendor. | | `422 delivery_not_available` | The vendor does not deliver to the address or on that date. | Check the zone and the dates again. | | `422 product_not_available` | A product is not offered on that date. | Read the date's product ids and choose again. | | `422 order_limits_not_met` | The order is under or over the vendor's limits. | Change the items. | | `422 vendor_not_allowed_for_customer` | The customer can order only from some vendors. | Offer another vendor. | | `422 validation_error` | A field breaks a rule of step 5. The message names it. | Fix the field. Do not send it again unchanged. | | `409 order_conflict` | The order cannot be placed in its current state. | Read the order, then decide. Do not retry unchanged. | ## Next - [Orders](/docs/meals/orders): every order route, the list and the events. - [Saving a card](/docs/meals/saving-a-card): let a customer pay with a saved card. - [Receive order webhooks](/docs/tutorials/receive-order-webhooks): learn when an order is paid. - [Errors](/docs/concepts/errors): every error code. --- # Receive order webhooks Build a small web server that Nurish'd calls when an order changes, check that each call is genuine, and update your own records. You will build a small web server. Nurish'd calls it when an order is created, paid, fulfilled, shipped, delivered, refunded or canceled. The server checks that the call really came from Nurish'd, reads the order, and updates its own records. A webhook is an HTTP request that Nurish'd sends to your server when something happens. The request body is a thin event. It names the order but does not contain it. Your server then reads the order with the API. See [Events](/docs/events/events) for the event object. ## Before you start - You finished [Set up your project](/docs/tutorials/set-up-your-project). Your project has the `nurishd` client file and a Sandbox key in `NURISHD_API_KEY`. - Your key has the scope `order:read`. It is needed to read orders and to choose order events. Run `check_key` from the setup tutorial to see your scopes. - Install the web server package for your language. | Language | Command | | ---------- | ------------------------------------------------------------------------ | | Python | `pip install flask` | | JavaScript | `npm install express` | | TypeScript | `npm install express` and `npm install --save-dev @types/express` | | Java | Replace `pom.xml` with the one below. It adds Javalin and a log package. | Java only. This `pom.xml` is the one from the setup tutorial plus two dependencies. Javalin is the web server and `slf4j-simple` prints its logs. ```xml 4.0.0 com.example nurishd-tutorial 1.0.0 17 UTF-8 com.fasterxml.jackson.core jackson-databind 2.17.2 io.javalin javalin 6.3.0 org.slf4j slf4j-simple 2.0.16 org.codehaus.mojo exec-maven-plugin 3.4.1 ``` ## 1. Settings and records Steps 1 to 3 build one server file, piece by piece. The complete file is in "The whole program" at the end. The server needs the signing secret, a table that says what each event means, and two places to keep state. A signing secret is a value that only you and Nurish'd know. Nurish'd uses it to sign every call. You get it in step 5. `orders` holds your records. `handled` holds the ids of events you already handled. Both live in memory here. A real app keeps them in its database, so they survive a restart. ```python SECRET = os.environ["NURISHD_WEBHOOK_SECRET"] TOLERANCE_SECONDS = 300 # What each order event means in your own records. STATUS = { "order.created": "received", "order.paid": "confirmed", "order.fulfilled": "fulfilled", "order.shipped": "shipped", "order.delivered": "delivered", "order.refunded": "refunded", "order.canceled": "canceled", } orders = {} # order id -> {"status": ..., "delivery_date": ...} handled = set() # ids of events you already handled ``` ```javascript const SECRET = process.env.NURISHD_WEBHOOK_SECRET; if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.'); const TOLERANCE_SECONDS = 300; // What each order event means in your own records. const STATUS = { 'order.created': 'received', 'order.paid': 'confirmed', 'order.fulfilled': 'fulfilled', 'order.shipped': 'shipped', 'order.delivered': 'delivered', 'order.refunded': 'refunded', 'order.canceled': 'canceled', }; const orders = new Map(); // order id -> { status, deliveryDate } const handled = new Set(); // ids of events you already handled ``` ```typescript const SECRET = process.env.NURISHD_WEBHOOK_SECRET; if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.'); const TOLERANCE_SECONDS = 300; interface WebhookEvent { id: string; type: string; data: { id: string }; } interface Order { order_delivery_date: string; } // What each order event means in your own records. const STATUS: Record = { 'order.created': 'received', 'order.paid': 'confirmed', 'order.fulfilled': 'fulfilled', 'order.shipped': 'shipped', 'order.delivered': 'delivered', 'order.refunded': 'refunded', 'order.canceled': 'canceled', }; const orders = new Map(); // order id -> your record const handled = new Set(); // ids of events you already handled ``` ```java private static final String SECRET = System.getenv("NURISHD_WEBHOOK_SECRET"); private static final long TOLERANCE_SECONDS = 300; // What each order event means in your own records. private static final Map STATUS = Map.of( "order.created", "received", "order.paid", "confirmed", "order.fulfilled", "fulfilled", "order.shipped", "shipped", "order.delivered", "delivered", "order.refunded", "refunded", "order.canceled", "canceled"); // order id -> status and delivery date private static final Map> orders = new ConcurrentHashMap<>(); // ids of events you already handled private static final Set handled = ConcurrentHashMap.newKeySet(); ``` ## 2. Check the signature Anyone can send a request to your address. The signature is how you know Nurish'd sent it. Each call has a `Nurishd-Signature` header. The header holds a time `t` and a signature `v1`. The signature is an HMAC-SHA256 of the text `t`, a dot, and the body. HMAC is a way to sign text with a secret. To check it, you build the same signature with your secret and compare. The function below also refuses a call that is more than five minutes old, so nobody can replay an old call. The comparison takes the same time whatever the input, which stops timing attacks. The [Verifying signatures](/docs/events/verifying-signatures) guide explains each step. The signature covers the exact bytes of the body. If you parse the JSON first and write it out again, the bytes can change and the check fails. So the server must read the raw body. Each framework gives it to you in a different way. - Flask: `request.get_data()` - Express: `express.raw({ type: 'application/json' })` in front of the route - Javalin: `ctx.bodyAsBytes()` ```python def verify_signature(raw_body, header, secret): """Returns True if the request came from Nurish'd and is fresh.""" if not header: return False timestamp = None signatures = [] for part in header.split(","): key, found, value = part.partition("=") if not found: continue key, value = key.strip(), value.strip() if key == "t": timestamp = value elif key == "v1": signatures.append(value) if timestamp is None or not timestamp.isdigit() or not signatures: return False if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS: return False expected = hmac.new( secret.encode("utf-8"), timestamp.encode("utf-8") + b"." + raw_body, hashlib.sha256, ).hexdigest() return any(hmac.compare_digest(expected, s.lower()) for s in signatures) ``` ```javascript /** Returns true if the request came from Nurish'd and is fresh. */ function verifySignature(rawBody, header, secret) { if (!header) return false; let timestamp = null; const signatures = []; for (const part of header.split(',')) { const index = part.indexOf('='); if (index === -1) continue; const key = part.slice(0, index).trim(); const value = part.slice(index + 1).trim(); if (key === 't') timestamp = value; if (key === 'v1') signatures.push(value); } if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false; const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)); if (age > TOLERANCE_SECONDS) return false; const expected = crypto .createHmac('sha256', secret) .update(Buffer.concat([Buffer.from(`${timestamp}.`), rawBody])) .digest(); return signatures.some((signature) => { if (!/^[0-9a-f]{64}$/i.test(signature)) return false; return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expected); }); } ``` ```typescript /** Returns true if the request came from Nurish'd and is fresh. */ function verifySignature( rawBody: Buffer, header: string | undefined, secret: string, ): boolean { if (!header) return false; let timestamp: string | null = null; const signatures: string[] = []; for (const part of header.split(',')) { const index = part.indexOf('='); if (index === -1) continue; const key = part.slice(0, index).trim(); const value = part.slice(index + 1).trim(); if (key === 't') timestamp = value; if (key === 'v1') signatures.push(value); } if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false; const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)); if (age > TOLERANCE_SECONDS) return false; const expected = crypto .createHmac('sha256', secret) .update(Buffer.concat([Buffer.from(`${timestamp}.`), rawBody])) .digest(); return signatures.some((signature) => { if (!/^[0-9a-f]{64}$/i.test(signature)) return false; return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expected); }); } ``` ```java /** Returns true if the request came from Nurish'd and is fresh. */ static boolean verifySignature(byte[] rawBody, String header, String secret) throws GeneralSecurityException { if (header == null) return false; String timestamp = null; List signatures = new ArrayList<>(); for (String part : header.split(",")) { int index = part.indexOf('='); if (index == -1) continue; String key = part.substring(0, index).trim(); String value = part.substring(index + 1).trim(); if (key.equals("t")) timestamp = value; if (key.equals("v1")) signatures.add(value); } if (timestamp == null || !timestamp.matches("\\d{1,12}") || signatures.isEmpty()) { return false; } long age = Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(timestamp)); if (age > TOLERANCE_SECONDS) return false; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8)); byte[] expected = mac.doFinal(rawBody); for (String signature : signatures) { if (!signature.matches("[0-9a-fA-F]{64}")) continue; if (MessageDigest.isEqual(HexFormat.of().parseHex(signature), expected)) return true; } return false; } ``` ## 3. The route The route answers `POST /webhooks/nurishd`. It does five things in order. 1. Read the raw body and check the signature. Answer `400` if the check fails, and do nothing else. 2. Ignore an event whose id is in `handled`. Nurish'd can send the same event more than once, and a repeat must do no harm. 3. For an order event, read the order with `GET /meals/v1/order/{order_id}/get/document`. Save the new status and the delivery date in `orders`. The event carries the order id in `data.id`. 4. Add the event id to `handled`. 5. Answer `200`. An event of another type, such as `ping`, is ignored and answered with `200`. If the order read fails with a `429` or a `5xx`, the route answers `500` so that Nurish'd sends the event again. Other errors, such as a `404` for an order your key cannot read, cannot be fixed by a retry. The route prints them and answers `200`. A `2xx` answer means success. Any other answer, a timeout or a connection error is a failure, and Nurish'd sends the event again with growing waits for up to three days. Nurish'd does not follow redirects. Answer fast. Here the route reads one order before it answers. A larger app answers first and does the work after, from a queue. ```python @app.post("/webhooks/nurishd") def receive(): # 1. Read the raw bytes and check the signature before anything else. raw_body = request.get_data() if not verify_signature(raw_body, request.headers.get("Nurishd-Signature"), SECRET): print("refused: bad signature") return "", 400 # 2. Ignore an event you already handled. event = json.loads(raw_body) if event["id"] in handled: print("ignored: already handled", event["id"]) return "", 200 # 3. For an order event, read the order and update your records. if event["type"] in STATUS: order_id = event["data"]["id"] try: order = call("GET", f"/meals/v1/order/{order_id}/get/document") orders[order_id] = { "status": STATUS[event["type"]], "delivery_date": order["order_delivery_date"], } print(event["type"], order_id, "->", orders[order_id]["status"]) except NurishdError as error: if error.status == 429 or error.status >= 500: return "", 500 # Nurish'd sends the event again later. print("cannot read order:", order_id, error.code) else: print("ignored type:", event["type"]) # 4. Remember the event and answer. handled.add(event["id"]) return "", 200 ``` ```javascript const app = express(); app.post( '/webhooks/nurishd', // 1. Keep the body as raw bytes. express.raw({ type: 'application/json' }), async (req, res) => { // 2. Check the signature before anything else. if (!verifySignature(req.body, req.get('Nurishd-Signature'), SECRET)) { console.log('refused: bad signature'); return res.sendStatus(400); } // 3. Ignore an event you already handled. const event = JSON.parse(req.body.toString('utf8')); if (handled.has(event.id)) { console.log('ignored: already handled', event.id); return res.sendStatus(200); } // 4. For an order event, read the order and update your records. if (event.type in STATUS) { const orderId = event.data.id; try { const order = await call( 'GET', `/meals/v1/order/${orderId}/get/document`, ); orders.set(orderId, { status: STATUS[event.type], deliveryDate: order.order_delivery_date, }); console.log( event.type, orderId, '->', orders.get(orderId).status, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; if (error.status === 429 || error.status >= 500) { return res.sendStatus(500); // Nurish'd sends the event again later. } console.log('cannot read order:', orderId, error.code); } } else { console.log('ignored type:', event.type); } // 5. Remember the event and answer. handled.add(event.id); res.sendStatus(200); }, ); ``` ```typescript const app = express(); app.post( '/webhooks/nurishd', // 1. Keep the body as raw bytes. express.raw({ type: 'application/json' }), async (req, res) => { // 2. Check the signature before anything else. if (!verifySignature(req.body, req.get('Nurishd-Signature'), SECRET)) { console.log('refused: bad signature'); return res.sendStatus(400); } // 3. Ignore an event you already handled. const event = JSON.parse(req.body.toString('utf8')) as WebhookEvent; if (handled.has(event.id)) { console.log('ignored: already handled', event.id); return res.sendStatus(200); } // 4. For an order event, read the order and update your records. if (event.type in STATUS) { const orderId = event.data.id; try { const order = await call( 'GET', `/meals/v1/order/${orderId}/get/document`, ); orders.set(orderId, { status: STATUS[event.type], deliveryDate: order.order_delivery_date, }); console.log( event.type, orderId, '->', orders.get(orderId)?.status, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; if (error.status === 429 || error.status >= 500) { return res.sendStatus(500); // Nurish'd sends the event again later. } console.log('cannot read order:', orderId, error.code); } } else { console.log('ignored type:', event.type); } // 5. Remember the event and answer. handled.add(event.id); res.sendStatus(200); }, ); ``` ```java app.post("/webhooks/nurishd", ctx -> { // 1. Read the raw bytes and check the signature before anything else. byte[] rawBody = ctx.bodyAsBytes(); if (!verifySignature(rawBody, ctx.header("Nurishd-Signature"), SECRET)) { System.out.println("refused: bad signature"); ctx.status(400); return; } // 2. Ignore an event you already handled. JsonNode event = Nurishd.JSON.readTree(rawBody); String eventId = event.path("id").asText(); String type = event.path("type").asText(); if (handled.contains(eventId)) { System.out.println("ignored: already handled " + eventId); ctx.status(200); return; } // 3. For an order event, read the order and update your records. if (STATUS.containsKey(type)) { String orderId = event.path("data").path("id").asText(); try { JsonNode order = Nurishd.call( "GET", "/meals/v1/order/%s/get/document".formatted(orderId)); orders.put(orderId, Map.of( "status", STATUS.get(type), "deliveryDate", order.path("order_delivery_date").asText())); System.out.println(type + " " + orderId + " -> " + STATUS.get(type)); } catch (Nurishd.NurishdException error) { if (error.status == 429 || error.status >= 500) { ctx.status(500); // Nurish'd sends the event again later. return; } System.out.println("cannot read order: " + orderId + " " + error.code); } } else { System.out.println("ignored type: " + type); } // 4. Remember the event and answer. handled.add(eventId); ctx.status(200); }); ``` ## 4. Get a public address Nurish'd cannot call `localhost`. While you build, a tunnel tool gives your computer a public HTTPS address that forwards to your server. Two common ones are ngrok and Cloudflare Tunnel. Follow their own setup guides, then start a tunnel to port 3000. - ngrok: `ngrok http 3000` - Cloudflare Tunnel: `cloudflared tunnel --url http://localhost:3000` The tool prints an address such as `https://example-name.trycloudflare.com`. Your webhook URL is that address plus `/webhooks/nurishd`. The URL must use `https`, have no user name or password and no fragment, and must not be `localhost` or a private IP address. See [Webhooks](/docs/events/webhooks). ## 5. Register the endpoint An endpoint tells Nurish'd where to send events. You can add one in the console, on the **Webhooks** page. This script does the same with `POST /developer/v1/webhook-endpoint/create/document`. It asks for the seven order events and prints the signing secret. Save the file for your language. For Java, save it as `src/main/java/tutorial/RegisterEndpoint.java`. ```python # file: register_endpoint.py import sys from nurishd import call # Run: python register_endpoint.py https://your-address.example.com/webhooks/nurishd url = sys.argv[1] created = call( "POST", "/developer/v1/webhook-endpoint/create/document", body={ "url": url, "events": [ "order.created", "order.paid", "order.fulfilled", "order.shipped", "order.delivered", "order.refunded", "order.canceled", ], "description": "Order updates", }, ) print("endpoint:", created["endpoint"]["endpoint_id"]) print("secret:", created["secret"]) ``` ```javascript // file: register-endpoint.js import { call } from './nurishd.js'; // Run: node register-endpoint.js https://your-address.example.com/webhooks/nurishd const url = process.argv[2]; const created = await call( 'POST', '/developer/v1/webhook-endpoint/create/document', { body: { url, events: [ 'order.created', 'order.paid', 'order.fulfilled', 'order.shipped', 'order.delivered', 'order.refunded', 'order.canceled', ], description: 'Order updates', }, }, ); console.log('endpoint:', created.endpoint.endpoint_id); console.log('secret:', created.secret); ``` ```typescript // file: register-endpoint.ts import { call } from './nurishd.ts'; interface Created { endpoint: { endpoint_id: string }; secret: string; } // Run: node register-endpoint.ts https://your-address.example.com/webhooks/nurishd const url = process.argv[2]; const created = await call( 'POST', '/developer/v1/webhook-endpoint/create/document', { body: { url, events: [ 'order.created', 'order.paid', 'order.fulfilled', 'order.shipped', 'order.delivered', 'order.refunded', 'order.canceled', ], description: 'Order updates', }, }, ); console.log('endpoint:', created.endpoint.endpoint_id); console.log('secret:', created.secret); ``` ```java // file: src/main/java/tutorial/RegisterEndpoint.java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import java.util.List; import java.util.Map; public class RegisterEndpoint { // Run with -Dexec.args="https://your-address.example.com/webhooks/nurishd" public static void main(String[] args) { Map body = Map.of( "url", args[0], "events", List.of( "order.created", "order.paid", "order.fulfilled", "order.shipped", "order.delivered", "order.refunded", "order.canceled"), "description", "Order updates"); JsonNode created = Nurishd.call("POST", "/developer/v1/webhook-endpoint/create/document", Map.of(), body); System.out.println("endpoint: " + created.path("endpoint").path("endpoint_id").asText()); System.out.println("secret: " + created.path("secret").asText()); } } ``` Run it with your webhook URL. - Python: `python register_endpoint.py https://example-name.trycloudflare.com/webhooks/nurishd` - JavaScript: `node register-endpoint.js https://example-name.trycloudflare.com/webhooks/nurishd` - TypeScript: `node register-endpoint.ts https://example-name.trycloudflare.com/webhooks/nurishd` - Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.RegisterEndpoint -Dexec.args="https://example-name.trycloudflare.com/webhooks/nurishd"` It prints this. The ids and the secret differ. ```text endpoint: endpoint-d223baf1 secret: nk-whsec-08812f306d0f7cfd84a4bc495b94c19b625f72ab381cb96ff3e915cb0838a1c5 ``` The secret is in the answer of the create call. Copy it now and keep it private like an API key. You can read it again in the console. Put it in a variable. macOS and Linux: ```bash export NURISHD_WEBHOOK_SECRET="nk-whsec-your-secret-here" ``` Windows PowerShell: ```powershell $env:NURISHD_WEBHOOK_SECRET = "nk-whsec-your-secret-here" ``` ## 6. Run the server Save the server for your language as `webhook.py`, `webhook.js`, `webhook.ts` or `src/main/java/tutorial/Webhook.java`. The complete files are in "The whole program". Start it in a terminal where `NURISHD_API_KEY` and `NURISHD_WEBHOOK_SECRET` are set. - Python: `python webhook.py` - JavaScript: `node webhook.js` - TypeScript: `node webhook.ts`, or `npx tsx webhook.ts` on Node older than 22.18 - Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.Webhook` The server listens on port 3000. To use another port, set the `PORT` variable and start the tunnel on that port. Leave the server running. Stop it with Ctrl+C. ## 7. Test it with Nurish'd In the console, open **Webhooks**, select your endpoint and select **Send test event**. Nurish'd sends a signed `ping` event. It is not an order event, so your server checks the signature and ignores it. The server prints this. ```text ignored type: ping ``` If the console shows the delivery as failed, see "If something goes wrong". ## 8. Test it without Nurish'd You can test the server without Nurish'd. This script builds a signed event the same way Nurish'd does and sends it to `localhost`. It sends four requests: a correct one, the same event again, one whose body was changed after signing, and one signed ten minutes ago. Save the file for your language. For Java, save it as `src/main/java/tutorial/SendTest.java`. ```python # file: send_test.py import hashlib import hmac import json import os import sys import time import requests SECRET = os.environ["NURISHD_WEBHOOK_SECRET"] URL = f"http://localhost:{os.environ.get('PORT', '3000')}/webhooks/nurishd" # Run: python send_test.py ORDER_ID order_id = sys.argv[1] if len(sys.argv) > 1 else "ORD-EXAMPLE-0001" def sign(timestamp, body): """Builds a Nurishd-Signature value the way Nurish'd does.""" message = str(timestamp).encode("utf-8") + b"." + body digest = hmac.new(SECRET.encode("utf-8"), message, hashlib.sha256).hexdigest() return f"t={timestamp},v1={digest}" def send(label, body, signature): res = requests.post( URL, data=body, headers={"Content-Type": "application/json", "Nurishd-Signature": signature}, timeout=10, ) print(label, res.status_code) now = int(time.time()) event = { "id": f"evt_test_{now}", "type": "order.paid", "created": "2026-04-01T15:06:30Z", "mode": "test", "data": {"object": "order", "id": order_id, "order": order_id, "customer": "customer-0001"}, } body = json.dumps(event, separators=(",", ":")).encode("utf-8") send("signed event:", body, sign(now, body)) send("same event again:", body, sign(now, body)) send("changed body:", body.replace(b"order.paid", b"order.canceled"), sign(now, body)) send("old timestamp:", body, sign(now - 600, body)) ``` ```javascript // file: send-test.js import crypto from 'node:crypto'; const SECRET = process.env.NURISHD_WEBHOOK_SECRET; if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.'); const URL = `http://localhost:${process.env.PORT ?? 3000}/webhooks/nurishd`; // Run: node send-test.js ORDER_ID const orderId = process.argv[2] ?? 'ORD-EXAMPLE-0001'; /** Builds a Nurishd-Signature value the way Nurish'd does. */ function sign(timestamp, body) { const digest = crypto .createHmac('sha256', SECRET) .update(`${timestamp}.${body}`) .digest('hex'); return `t=${timestamp},v1=${digest}`; } async function send(label, body, signature) { const res = await fetch(URL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Nurishd-Signature': signature, }, body, }); console.log(label, res.status); } const now = Math.floor(Date.now() / 1000); const body = JSON.stringify({ id: `evt_test_${now}`, type: 'order.paid', created: '2026-04-01T15:06:30Z', mode: 'test', data: { object: 'order', id: orderId, order: orderId, customer: 'customer-0001', }, }); await send('signed event:', body, sign(now, body)); await send('same event again:', body, sign(now, body)); await send( 'changed body:', body.replace('order.paid', 'order.canceled'), sign(now, body), ); await send('old timestamp:', body, sign(now - 600, body)); ``` ```typescript // file: send-test.ts import crypto from 'node:crypto'; const SECRET = process.env.NURISHD_WEBHOOK_SECRET; if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.'); const URL = `http://localhost:${process.env.PORT ?? 3000}/webhooks/nurishd`; // Run: node send-test.ts ORDER_ID const orderId = process.argv[2] ?? 'ORD-EXAMPLE-0001'; /** Builds a Nurishd-Signature value the way Nurish'd does. */ function sign(timestamp: number, body: string): string { const digest = crypto .createHmac('sha256', SECRET as string) .update(`${timestamp}.${body}`) .digest('hex'); return `t=${timestamp},v1=${digest}`; } async function send(label: string, body: string, signature: string) { const res = await fetch(URL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Nurishd-Signature': signature, }, body, }); console.log(label, res.status); } const now = Math.floor(Date.now() / 1000); const body = JSON.stringify({ id: `evt_test_${now}`, type: 'order.paid', created: '2026-04-01T15:06:30Z', mode: 'test', data: { object: 'order', id: orderId, order: orderId, customer: 'customer-0001', }, }); await send('signed event:', body, sign(now, body)); await send('same event again:', body, sign(now, body)); await send( 'changed body:', body.replace('order.paid', 'order.canceled'), sign(now, body), ); await send('old timestamp:', body, sign(now - 600, body)); ``` ```java // file: src/main/java/tutorial/SendTest.java package tutorial; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.HexFormat; import java.util.Map; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class SendTest { static final String SECRET = System.getenv("NURISHD_WEBHOOK_SECRET"); static final String URL = "http://localhost:" + System.getenv().getOrDefault("PORT", "3000") + "/webhooks/nurishd"; /** Builds a Nurishd-Signature value the way Nurish'd does. */ static String sign(long timestamp, String body) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); byte[] digest = mac.doFinal((timestamp + "." + body).getBytes(StandardCharsets.UTF_8)); return "t=" + timestamp + ",v1=" + HexFormat.of().formatHex(digest); } static void send(String label, String body, String signature) throws Exception { HttpRequest request = HttpRequest.newBuilder(URI.create(URL)) .header("Content-Type", "application/json") .header("Nurishd-Signature", signature) .POST(HttpRequest.BodyPublishers.ofString(body)) .build(); HttpResponse res = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(label + " " + res.statusCode()); } // Run with -Dexec.args="ORDER_ID" public static void main(String[] args) throws Exception { String orderId = args.length > 0 ? args[0] : "ORD-EXAMPLE-0001"; long now = System.currentTimeMillis() / 1000; String body = Nurishd.JSON.writeValueAsString(Map.of( "id", "evt_test_" + now, "type", "order.paid", "created", "2026-04-01T15:06:30Z", "mode", "test", "data", Map.of("object", "order", "id", orderId, "order", orderId, "customer", "customer-0001"))); send("signed event:", body, sign(now, body)); send("same event again:", body, sign(now, body)); send("changed body:", body.replace("order.paid", "order.canceled"), sign(now, body)); send("old timestamp:", body, sign(now - 600, body)); } } ``` Run it in a second terminal where `NURISHD_WEBHOOK_SECRET` is set. Pass the id of one of your orders as the argument. Without an argument it uses `ORD-EXAMPLE-0001`, which the real Sandbox does not know. - Python: `python send_test.py ORDER_ID` - JavaScript: `node send-test.js ORDER_ID` - TypeScript: `node send-test.ts ORDER_ID` - Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.SendTest -Dexec.args="ORDER_ID"` The script prints the answer of each request. ```text signed event: 200 same event again: 200 changed body: 400 old timestamp: 400 ``` The server terminal prints what it did with each one. ```text order.paid ORD-EXAMPLE-0001 -> confirmed ignored: already handled evt_test_1795112345 refused: bad signature refused: bad signature ``` The signed event is accepted and the order is marked `confirmed`. The repeat is ignored. The changed body and the old timestamp are refused with `400`. ## 9. If you miss an event If your server is down or answers with an error, Nurish'd sends the event again for up to three days. You can also read what you missed. `GET /developer/v1/event/query/documents` lists events from the last 30 days. Ask only for events at or after the time of the last one you handled, and skip ids you already handled. The [Events](/docs/events/events) guide shows this pattern. ## The whole program Each language has one server file. The registration script and the test script are shown in full in steps 5 and 8. ```python # file: webhook.py import hashlib import hmac import json import os import time from flask import Flask, request from nurishd import NurishdError, call SECRET = os.environ["NURISHD_WEBHOOK_SECRET"] TOLERANCE_SECONDS = 300 # What each order event means in your own records. STATUS = { "order.created": "received", "order.paid": "confirmed", "order.fulfilled": "fulfilled", "order.shipped": "shipped", "order.delivered": "delivered", "order.refunded": "refunded", "order.canceled": "canceled", } orders = {} # order id -> {"status": ..., "delivery_date": ...} handled = set() # ids of events you already handled app = Flask(__name__) def verify_signature(raw_body, header, secret): """Returns True if the request came from Nurish'd and is fresh.""" if not header: return False timestamp = None signatures = [] for part in header.split(","): key, found, value = part.partition("=") if not found: continue key, value = key.strip(), value.strip() if key == "t": timestamp = value elif key == "v1": signatures.append(value) if timestamp is None or not timestamp.isdigit() or not signatures: return False if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS: return False expected = hmac.new( secret.encode("utf-8"), timestamp.encode("utf-8") + b"." + raw_body, hashlib.sha256, ).hexdigest() return any(hmac.compare_digest(expected, s.lower()) for s in signatures) @app.post("/webhooks/nurishd") def receive(): # 1. Read the raw bytes and check the signature before anything else. raw_body = request.get_data() if not verify_signature(raw_body, request.headers.get("Nurishd-Signature"), SECRET): print("refused: bad signature") return "", 400 # 2. Ignore an event you already handled. event = json.loads(raw_body) if event["id"] in handled: print("ignored: already handled", event["id"]) return "", 200 # 3. For an order event, read the order and update your records. if event["type"] in STATUS: order_id = event["data"]["id"] try: order = call("GET", f"/meals/v1/order/{order_id}/get/document") orders[order_id] = { "status": STATUS[event["type"]], "delivery_date": order["order_delivery_date"], } print(event["type"], order_id, "->", orders[order_id]["status"]) except NurishdError as error: if error.status == 429 or error.status >= 500: return "", 500 # Nurish'd sends the event again later. print("cannot read order:", order_id, error.code) else: print("ignored type:", event["type"]) # 4. Remember the event and answer. handled.add(event["id"]) return "", 200 if __name__ == "__main__": app.run(port=int(os.environ.get("PORT", "3000"))) ``` ```javascript // file: webhook.js import crypto from 'node:crypto'; import express from 'express'; import { NurishdError, call } from './nurishd.js'; const SECRET = process.env.NURISHD_WEBHOOK_SECRET; if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.'); const TOLERANCE_SECONDS = 300; // What each order event means in your own records. const STATUS = { 'order.created': 'received', 'order.paid': 'confirmed', 'order.fulfilled': 'fulfilled', 'order.shipped': 'shipped', 'order.delivered': 'delivered', 'order.refunded': 'refunded', 'order.canceled': 'canceled', }; const orders = new Map(); // order id -> { status, deliveryDate } const handled = new Set(); // ids of events you already handled /** Returns true if the request came from Nurish'd and is fresh. */ function verifySignature(rawBody, header, secret) { if (!header) return false; let timestamp = null; const signatures = []; for (const part of header.split(',')) { const index = part.indexOf('='); if (index === -1) continue; const key = part.slice(0, index).trim(); const value = part.slice(index + 1).trim(); if (key === 't') timestamp = value; if (key === 'v1') signatures.push(value); } if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false; const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)); if (age > TOLERANCE_SECONDS) return false; const expected = crypto .createHmac('sha256', secret) .update(Buffer.concat([Buffer.from(`${timestamp}.`), rawBody])) .digest(); return signatures.some((signature) => { if (!/^[0-9a-f]{64}$/i.test(signature)) return false; return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expected); }); } const app = express(); app.post( '/webhooks/nurishd', // 1. Keep the body as raw bytes. express.raw({ type: 'application/json' }), async (req, res) => { // 2. Check the signature before anything else. if (!verifySignature(req.body, req.get('Nurishd-Signature'), SECRET)) { console.log('refused: bad signature'); return res.sendStatus(400); } // 3. Ignore an event you already handled. const event = JSON.parse(req.body.toString('utf8')); if (handled.has(event.id)) { console.log('ignored: already handled', event.id); return res.sendStatus(200); } // 4. For an order event, read the order and update your records. if (event.type in STATUS) { const orderId = event.data.id; try { const order = await call( 'GET', `/meals/v1/order/${orderId}/get/document`, ); orders.set(orderId, { status: STATUS[event.type], deliveryDate: order.order_delivery_date, }); console.log( event.type, orderId, '->', orders.get(orderId).status, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; if (error.status === 429 || error.status >= 500) { return res.sendStatus(500); // Nurish'd sends the event again later. } console.log('cannot read order:', orderId, error.code); } } else { console.log('ignored type:', event.type); } // 5. Remember the event and answer. handled.add(event.id); res.sendStatus(200); }, ); app.listen(Number(process.env.PORT ?? 3000), () => { console.log('Listening for webhooks'); }); ``` ```typescript // file: webhook.ts import crypto from 'node:crypto'; import express from 'express'; import { NurishdError, call } from './nurishd.ts'; const SECRET = process.env.NURISHD_WEBHOOK_SECRET; if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.'); const TOLERANCE_SECONDS = 300; interface WebhookEvent { id: string; type: string; data: { id: string }; } interface Order { order_delivery_date: string; } // What each order event means in your own records. const STATUS: Record = { 'order.created': 'received', 'order.paid': 'confirmed', 'order.fulfilled': 'fulfilled', 'order.shipped': 'shipped', 'order.delivered': 'delivered', 'order.refunded': 'refunded', 'order.canceled': 'canceled', }; const orders = new Map(); // order id -> your record const handled = new Set(); // ids of events you already handled /** Returns true if the request came from Nurish'd and is fresh. */ function verifySignature( rawBody: Buffer, header: string | undefined, secret: string, ): boolean { if (!header) return false; let timestamp: string | null = null; const signatures: string[] = []; for (const part of header.split(',')) { const index = part.indexOf('='); if (index === -1) continue; const key = part.slice(0, index).trim(); const value = part.slice(index + 1).trim(); if (key === 't') timestamp = value; if (key === 'v1') signatures.push(value); } if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false; const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)); if (age > TOLERANCE_SECONDS) return false; const expected = crypto .createHmac('sha256', secret) .update(Buffer.concat([Buffer.from(`${timestamp}.`), rawBody])) .digest(); return signatures.some((signature) => { if (!/^[0-9a-f]{64}$/i.test(signature)) return false; return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expected); }); } const app = express(); app.post( '/webhooks/nurishd', // 1. Keep the body as raw bytes. express.raw({ type: 'application/json' }), async (req, res) => { // 2. Check the signature before anything else. if (!verifySignature(req.body, req.get('Nurishd-Signature'), SECRET)) { console.log('refused: bad signature'); return res.sendStatus(400); } // 3. Ignore an event you already handled. const event = JSON.parse(req.body.toString('utf8')) as WebhookEvent; if (handled.has(event.id)) { console.log('ignored: already handled', event.id); return res.sendStatus(200); } // 4. For an order event, read the order and update your records. if (event.type in STATUS) { const orderId = event.data.id; try { const order = await call( 'GET', `/meals/v1/order/${orderId}/get/document`, ); orders.set(orderId, { status: STATUS[event.type], deliveryDate: order.order_delivery_date, }); console.log( event.type, orderId, '->', orders.get(orderId)?.status, ); } catch (error) { if (!(error instanceof NurishdError)) throw error; if (error.status === 429 || error.status >= 500) { return res.sendStatus(500); // Nurish'd sends the event again later. } console.log('cannot read order:', orderId, error.code); } } else { console.log('ignored type:', event.type); } // 5. Remember the event and answer. handled.add(event.id); res.sendStatus(200); }, ); app.listen(Number(process.env.PORT ?? 3000), () => { console.log('Listening for webhooks'); }); ``` ```java // file: src/main/java/tutorial/Webhook.java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import io.javalin.Javalin; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class Webhook { private static final String SECRET = System.getenv("NURISHD_WEBHOOK_SECRET"); private static final long TOLERANCE_SECONDS = 300; // What each order event means in your own records. private static final Map STATUS = Map.of( "order.created", "received", "order.paid", "confirmed", "order.fulfilled", "fulfilled", "order.shipped", "shipped", "order.delivered", "delivered", "order.refunded", "refunded", "order.canceled", "canceled"); // order id -> status and delivery date private static final Map> orders = new ConcurrentHashMap<>(); // ids of events you already handled private static final Set handled = ConcurrentHashMap.newKeySet(); /** Returns true if the request came from Nurish'd and is fresh. */ static boolean verifySignature(byte[] rawBody, String header, String secret) throws GeneralSecurityException { if (header == null) return false; String timestamp = null; List signatures = new ArrayList<>(); for (String part : header.split(",")) { int index = part.indexOf('='); if (index == -1) continue; String key = part.substring(0, index).trim(); String value = part.substring(index + 1).trim(); if (key.equals("t")) timestamp = value; if (key.equals("v1")) signatures.add(value); } if (timestamp == null || !timestamp.matches("\\d{1,12}") || signatures.isEmpty()) { return false; } long age = Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(timestamp)); if (age > TOLERANCE_SECONDS) return false; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8)); byte[] expected = mac.doFinal(rawBody); for (String signature : signatures) { if (!signature.matches("[0-9a-fA-F]{64}")) continue; if (MessageDigest.isEqual(HexFormat.of().parseHex(signature), expected)) return true; } return false; } public static void main(String[] args) { if (SECRET == null || SECRET.isBlank()) { throw new IllegalStateException("Set NURISHD_WEBHOOK_SECRET first."); } int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "3000")); Javalin app = Javalin.create(); app.post("/webhooks/nurishd", ctx -> { // 1. Read the raw bytes and check the signature before anything else. byte[] rawBody = ctx.bodyAsBytes(); if (!verifySignature(rawBody, ctx.header("Nurishd-Signature"), SECRET)) { System.out.println("refused: bad signature"); ctx.status(400); return; } // 2. Ignore an event you already handled. JsonNode event = Nurishd.JSON.readTree(rawBody); String eventId = event.path("id").asText(); String type = event.path("type").asText(); if (handled.contains(eventId)) { System.out.println("ignored: already handled " + eventId); ctx.status(200); return; } // 3. For an order event, read the order and update your records. if (STATUS.containsKey(type)) { String orderId = event.path("data").path("id").asText(); try { JsonNode order = Nurishd.call( "GET", "/meals/v1/order/%s/get/document".formatted(orderId)); orders.put(orderId, Map.of( "status", STATUS.get(type), "deliveryDate", order.path("order_delivery_date").asText())); System.out.println(type + " " + orderId + " -> " + STATUS.get(type)); } catch (Nurishd.NurishdException error) { if (error.status == 429 || error.status >= 500) { ctx.status(500); // Nurish'd sends the event again later. return; } System.out.println("cannot read order: " + orderId + " " + error.code); } } else { System.out.println("ignored type: " + type); } // 4. Remember the event and answer. handled.add(eventId); ctx.status(200); }); app.start(port); } } ``` ## If something goes wrong | What you see | Why | What to do | | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | | The server prints `refused: bad signature` for a real delivery | The secret is wrong, the body was changed before the check, or your computer clock is off by over 5 minutes. | Copy the secret from the console. Make sure nothing parses the body before the check. Fix the clock. | | The console shows a failed delivery and the server prints nothing | The address does not reach your server. | Check that the tunnel runs, that the URL ends with `/webhooks/nurishd` and that the port matches. | | `403 scope_not_granted` when you register | The key cannot see one of the order events. | Use a key with the `order:read` scope. See [Scopes](/docs/concepts/scopes). | | `422 validation_error` when you register | The URL is not a public `https` address. | Use the tunnel address. It cannot be `http`, `localhost` or a private IP. | | `409 webhook_endpoint_limit_reached` when you register | The company has 10 endpoints in this environment. | Delete an endpoint you do not use, in the console. | | The server prints `cannot read order: ... not_found` | The order does not exist, or it belongs to another company or environment. | Use an order your Sandbox key placed. A sample id such as `ORD-EXAMPLE-0001` is unknown to the real Sandbox. | | The server prints `cannot read order: ... connection_not_active` | The customer ended the connection, so you can no longer read their orders. | Nothing to fix. The route skips the order. | | `Set NURISHD_WEBHOOK_SECRET first.` or `KeyError` | The variable is not set in this terminal. | Set it again as in step 5, then start the server. | | `EADDRINUSE` or `Address already in use` | Something else uses port 3000. | Set `PORT` to a free port and start the tunnel on it. | ## Next - [Webhooks](/docs/events/webhooks): endpoints, pausing and retries. - [Verifying signatures](/docs/events/verifying-signatures): roll a signing secret without missing events. - [Orders](/docs/meals/orders): order fields and statuses. - [Place a meal order](/docs/tutorials/place-a-meal-order): create the orders this server hears about. --- # 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](/docs/tutorials/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](/docs/get-started/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](/docs/concepts/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"]) ``` ```javascript 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); } } ``` ```typescript 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>('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>( '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); } } ``` ```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; 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 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. ```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.") ``` ```javascript 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.'); } ``` ```typescript async function showProfile(specialistId: string) { 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.'); } ``` ```java 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. ```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)}") ``` ```javascript 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(', ')}`); } } ``` ```typescript 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('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(', ')}`); } } ``` ```java 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> 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. ```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) ``` ```javascript 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); } } ``` ```typescript 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); } } ``` ```java 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: ```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() ``` ```javascript // 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(); ``` ```typescript // 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>('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>( '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( '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('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(); ``` ```java // 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 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> 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](/docs/concepts/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](/docs/tutorials/receive-order-webhooks) shows a small server in each language. ## Next - [Booking a visit](/docs/care/booking-a-visit): every filter, field and error of the booking routes. - [Book a visit with a dietitian](/docs/tutorials/book-a-dietitian-visit): use an open time to book a visit. - [Pagination](/docs/concepts/pagination): read more than one page. - [Errors](/docs/concepts/errors): every error code. --- # 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](/docs/tutorials/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](/docs/care/baa). - 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](/docs/care/connecting-a-patient) and [Booking a visit](/docs/care/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)) ``` ```javascript 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)); } ``` ```typescript 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)); } ``` ```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; 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](/docs/concepts/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"]) ``` ```javascript 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); } ``` ```typescript 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); } ``` ```java static void createPatient() throws IOException { Map address = Map.of( "line1", "10 Example Street", "city", "Toronto", "state", PATIENT_STATE, "postal_code", "M5V 2T6", "country", "CA"); Map 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"` ```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](/docs/care/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.") ``` ```javascript 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.', ); } } ``` ```typescript 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.', ); } } ``` ```java 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."); } } ``` ```text 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: ```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](/docs/care/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}") ``` ```javascript 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}`); } } ``` ```typescript 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}`); } } ``` ```java 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); } } ``` ```text 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: ```text 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](/docs/tutorials/show-dietitians) 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']}.") ``` ```javascript 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}.`, ); } ``` ```typescript async function findOpenTime(): Promise { 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: 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}.`, ); } ``` ```java static String[] findOpenTime() { Instant start = Instant.now().truncatedTo(ChronoUnit.SECONDS); Map 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 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() + "."); } ``` ```text 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: ```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']}") ``` ```javascript 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}`, ); } } ``` ```typescript 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}`, ); } } ``` ```java 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()); } } ``` ```text 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:00Z ``` ## 7. Cancel the booking > **Warning.** A visit canceled less than 24 hours before it starts may be charged a late-cancellation fee, billed to the patient. Tell the patient before you cancel. `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']}.") ``` ```javascript 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}.`); } ``` ```typescript 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}.`); } ``` ```java 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() + "."); } ``` ```text python visit.py cancel Booking booking-0001 is now meeting_cancelled. ``` 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) ``` ```javascript 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); } } ``` ```typescript const HINTS: Record = { 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); } } ``` ```java static final Map 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 ```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() ``` ```javascript // 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(); ``` ```typescript // 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 = { 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( '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 { 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: 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] 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(); ``` ```java // 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 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 address = Map.of( "line1", "10 Example Street", "city", "Toronto", "state", PATIENT_STATE, "postal_code", "M5V 2T6", "country", "CA"); Map 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 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 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](/docs/care/baa). | | `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](/docs/care/connecting-a-patient): statuses, revoking a connection and return URLs. - [Saving a card](/docs/care/saving-a-card): the browser part of step 4. - [Booking a visit](/docs/care/booking-a-visit): every filter and field. - [Show dietitians and their open times](/docs/tutorials/show-dietitians): display the choices to a patient. - [Read visit reports](/docs/tutorials/read-visit-reports): read the report after a visit. --- # Read visit reports Write a command-line program that finds the signed report of a dietitian visit, prints its sections and downloads the files in it. After a visit, the dietitian writes a report and signs it. You build a command-line program that finds a signed report, lists reports, prints the sections of one report and downloads the file of a section. The API calls a dietitian a **specialist** and 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](/docs/tutorials/set-up-your-project). Your project has the `nurishd` client file and a Sandbox key in `NURISHD_API_KEY`. - Your key has the scope `report:read`. It reads reports and sees `report.signed` events. Step 1 also needs `booking:write`. 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. See [BAA handling](/docs/care/baa). - A booked visit of a Sandbox patient. Run the tutorial [Book a visit with a dietitian](/docs/tutorials/book-a-dietitian-visit) up to `show`, and stop before `cancel`. Its `show` command prints the booking id. A canceled visit cannot be completed. - The patient allowed reports. When you create a patient with a key that holds `report:read`, the patient is asked to allow `care.reports`. See [Connections](/docs/concepts/connections). - Python only: the program uses the `requests` package from the setup tutorial. ## 1. Complete a visit in the Sandbox In the Sandbox no real visit happens, so nothing signs a report. The Sandbox has a test helper for this. `POST /developer/v1/test-helper/booking/{booking_id}/complete/document` marks a visit of yours as done and signs a sample report. Its content is invented. The helper works only with a Sandbox key. A Production key gets `403 test_mode_only`. In Production there is no helper: the dietitian signs a report after a real visit, and you learn about it in step 2. The program starts with its imports and the function for this step. ```python import sys from pathlib import Path import requests from nurishd import NurishdError, call EXTENSIONS = { "application/pdf": ".pdf", "image/png": ".png", "image/jpeg": ".jpg", } HINTS = { "scope_not_granted": "Your key lacks a scope, or your company has no signed BAA.", "test_mode_only": "This helper works with a Sandbox key only. Use a key that starts with nk-test-.", "booking_not_completable": "The booking was canceled or is already completed. Use a booking in status booked.", "connection_scope_not_granted": "The patient does not share reports. Connect the patient again and ask for care.reports.", "connection_not_active": "The patient revoked the connection. You can no longer read this patient's reports.", "not_found": "Nothing with this id is visible to your company. Check the id.", } def complete_booking(booking_id): path = f"/developer/v1/test-helper/booking/{booking_id}/complete/document" done = call("POST", path) print(f"Booking {done['booking_id']} is now {done['status']}.") print(f"A sample report was signed: {done['report_id']}") ``` ```javascript import { writeFileSync } from 'node:fs'; import { NurishdError, call } from './nurishd.js'; const EXTENSIONS = { 'application/pdf': '.pdf', 'image/png': '.png', 'image/jpeg': '.jpg', }; const HINTS = { scope_not_granted: 'Your key lacks a scope, or your company has no signed BAA.', test_mode_only: 'This helper works with a Sandbox key only. Use a key that starts with nk-test-.', booking_not_completable: 'The booking was canceled or is already completed. Use a booking in status booked.', connection_scope_not_granted: 'The patient does not share reports. Connect the patient again and ask for care.reports.', connection_not_active: "The patient revoked the connection. You can no longer read this patient's reports.", not_found: 'Nothing with this id is visible to your company. Check the id.', }; async function completeBooking(bookingId) { const path = `/developer/v1/test-helper/booking/${bookingId}/complete/document`; const done = await call('POST', path); console.log(`Booking ${done.booking_id} is now ${done.status}.`); console.log(`A sample report was signed: ${done.report_id}`); } ``` ```typescript import { writeFileSync } from 'node:fs'; import { NurishdError, call } from './nurishd.ts'; import type { Page } from './nurishd.ts'; async function completeBooking(bookingId: string) { const path = `/developer/v1/test-helper/booking/${bookingId}/complete/document`; const done = await call<{ booking_id: string; report_id: string; status: string; }>('POST', path); console.log(`Booking ${done.booking_id} is now ${done.status}.`); console.log(`A sample report was signed: ${done.report_id}`); } ``` ```java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import tutorial.Nurishd.NurishdException; static void completeBooking(String bookingId) { String path = "/developer/v1/test-helper/booking/%s/complete/document".formatted(bookingId); JsonNode done = Nurishd.call("POST", path); System.out.println("Booking " + done.path("booking_id").asText() + " is now " + done.path("status").asText() + "."); System.out.println("A sample report was signed: " + done.path("report_id").asText()); } ``` Run it with the booking id from the booking tutorial. Replace `python reports.py` with the command of your language. - Python: `python reports.py complete BOOKING_ID` - JavaScript: `node reports.js complete BOOKING_ID` - TypeScript: `node reports.ts complete BOOKING_ID` - Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.Reports -Dexec.args="complete BOOKING_ID"` ```text python reports.py complete booking-0001 Booking booking-0001 is now meeting_completed. A sample report was signed: report-0001 ``` The visit is now `meeting_completed`, and the report id is in the answer. A booking that was canceled or is already completed answers `409 booking_not_completable`. ## 2. Learn that a report is signed You do not need to keep asking the reports route. Nurish'd raises a `report.signed` event when a dietitian signs the report of a visit your company booked. An event is thin: it holds ids and never the report. `data.id` is the report id, and `data.booking` is the visit. A webhook sends events to your server as they happen. See [Receive order webhooks](/docs/tutorials/receive-order-webhooks) for a server that receives them. Here you read the events by hand, with `GET /developer/v1/event/query/documents`. The `type` filter keeps one event type. Events are kept for 30 days, and your key sees only types its scopes allow. ```python def list_events(): answer = call( "GET", "/developer/v1/event/query/documents", params={"type": "report.signed", "size": 10}, ) if not answer["data"]: print("No report.signed event yet. Wait a few seconds and run it again.") for event in answer["data"]: data = event["data"] print(f"{event['created']}: report {data['id']} for booking {data.get('booking')}") ``` ```javascript async function listEvents() { const answer = await call('GET', '/developer/v1/event/query/documents', { params: { type: 'report.signed', size: 10 }, }); if (answer.data.length === 0) { console.log( 'No report.signed event yet. Wait a few seconds and run it again.', ); } for (const event of answer.data) { console.log( `${event.created}: report ${event.data.id} for booking ${event.data.booking}`, ); } } ``` ```typescript async function listEvents() { const answer = await call>( 'GET', '/developer/v1/event/query/documents', { params: { type: 'report.signed', size: 10 } }, ); if (answer.data.length === 0) { console.log( 'No report.signed event yet. Wait a few seconds and run it again.', ); } for (const event of answer.data) { console.log( `${event.created}: report ${event.data.id} for booking ${event.data.booking}`, ); } } ``` ```java static void listEvents() { JsonNode answer = Nurishd.call( "GET", "/developer/v1/event/query/documents", Map.of("type", "report.signed", "size", 10), null); if (answer.path("data").isEmpty()) { System.out.println("No report.signed event yet. Wait a few seconds and run it again."); } for (JsonNode event : answer.path("data")) { System.out.println(event.path("created").asText() + ": report " + event.path("data").path("id").asText() + " for booking " + event.path("data").path("booking").asText()); } } ``` The event follows shortly after the helper answers. If the list is empty, wait a few seconds and run it again. ```text python reports.py events 2026-11-19T15:10:00Z: report report-0001 for booking booking-0001 ``` ## 3. List the reports `GET /care/v1/report/query/documents` returns a page of signed reports, newest first. All filters are optional: `patient`, `booking`, `from`, `to`, `page` and `size`. The list is thin. It holds ids and `signed_at`. You read one report to get its sections. If you ask for one `booking` and no report of it is known yet, the call also looks for a signed report of that visit. A report whose event you missed still shows up. ```python def list_reports(booking_id=None): params = {"booking": booking_id} if booking_id else {} answer = call("GET", "/care/v1/report/query/documents", params=params) if not answer["data"]: print("No signed report found.") for item in answer["data"]: print(f"{item['report_id']}: booking {item['booking_id']}, signed {item['signed_at']}") ``` ```javascript async function listReports(bookingId) { const params = bookingId ? { booking: bookingId } : {}; const answer = await call('GET', '/care/v1/report/query/documents', { params, }); if (answer.data.length === 0) console.log('No signed report found.'); for (const item of answer.data) { console.log( `${item.report_id}: booking ${item.booking_id}, signed ${item.signed_at}`, ); } } ``` ```typescript async function listReports(bookingId?: string) { const params: Record = bookingId ? { booking: bookingId } : {}; const answer = await call>( 'GET', '/care/v1/report/query/documents', { params }, ); if (answer.data.length === 0) console.log('No signed report found.'); for (const item of answer.data) { console.log( `${item.report_id}: booking ${item.booking_id}, signed ${item.signed_at}`, ); } } ``` ```java static void listReports(String bookingId) { Map params = bookingId == null ? Map.of() : Map.of("booking", bookingId); JsonNode answer = Nurishd.call("GET", "/care/v1/report/query/documents", params, null); if (answer.path("data").isEmpty()) { System.out.println("No signed report found."); } for (JsonNode item : answer.path("data")) { System.out.println(item.path("report_id").asText() + ": booking " + item.path("booking_id").asText() + ", signed " + item.path("signed_at").asText()); } } ``` ```text python reports.py list booking-0001 report-0001: booking booking-0001, signed 2026-11-19T15:10:00Z ``` You see only signed reports. A report that is not signed yet is not visible to you, so it is not in the list. You also see only reports of visits your company booked, for patients whose connection is still `active`. ## 4. Read one report `GET /care/v1/report/{report_id}/get/document` returns the report with its sections, lowest `section_order` first. Each section has a name, a `section_type` (`note`, `table`, `image`, `pdf` or `signature`) and two fields that matter here: - `section_content` holds the text of the section as Markdown. An `image` or a `pdf` section has none. - `has_file` is `true` when the section has a file to download. The program decides by these two fields, not by the type. It prints the text if there is any. It says so if there is a file. ```python def show_report(report_id): report = call("GET", f"/care/v1/report/{report_id}/get/document") name = report["specialist_snapshot"].get("full_name", "unknown") print(f"Report {report['report_id']}, signed {report['signed_at']} by {name}") for section in sorted(report["sections"], key=lambda s: s["section_order"]): print() print(f"== {section['section_name']} ({section['section_type']}) ==") if section.get("section_content"): print(section["section_content"]) if section["has_file"]: print(f"A file is attached. Run: file {report_id} {section['section_id']}") ``` ```javascript async function showReport(reportId) { const report = await call( 'GET', `/care/v1/report/${reportId}/get/document`, ); const name = report.specialist_snapshot.full_name ?? 'unknown'; console.log( `Report ${report.report_id}, signed ${report.signed_at} by ${name}`, ); const sections = [...report.sections].sort( (a, b) => a.section_order - b.section_order, ); for (const section of sections) { console.log(); console.log(`== ${section.section_name} (${section.section_type}) ==`); if (section.section_content) console.log(section.section_content); if (section.has_file) { console.log( `A file is attached. Run: file ${reportId} ${section.section_id}`, ); } } } ``` ```typescript async function showReport(reportId: string) { const report = await call( 'GET', `/care/v1/report/${reportId}/get/document`, ); const name = report.specialist_snapshot.full_name ?? 'unknown'; console.log( `Report ${report.report_id}, signed ${report.signed_at} by ${name}`, ); const sections = [...report.sections].sort( (a, b) => a.section_order - b.section_order, ); for (const section of sections) { console.log(); console.log(`== ${section.section_name} (${section.section_type}) ==`); if (section.section_content) console.log(section.section_content); if (section.has_file) { console.log( `A file is attached. Run: file ${reportId} ${section.section_id}`, ); } } } ``` ```java static void showReport(String reportId) { JsonNode report = Nurishd.call("GET", "/care/v1/report/%s/get/document".formatted(reportId)); String name = report.path("specialist_snapshot").path("full_name").asText("unknown"); System.out.println("Report " + report.path("report_id").asText() + ", signed " + report.path("signed_at").asText() + " by " + name); List sections = new ArrayList<>(); report.path("sections").forEach(sections::add); sections.sort(Comparator.comparingInt(s -> s.path("section_order").asInt())); for (JsonNode section : sections) { System.out.println(); System.out.println("== " + section.path("section_name").asText() + " (" + section.path("section_type").asText() + ") =="); if (!section.path("section_content").asText("").isEmpty()) { System.out.println(section.path("section_content").asText()); } if (section.path("has_file").asBoolean()) { System.out.println("A file is attached. Run: file " + reportId + " " + section.path("section_id").asText()); } } } ``` ```text python reports.py show report-0001 Report report-0001, signed 2026-11-19T15:10:00Z by Maya Okafor == Summary (note) == You are on track. Keep the plan for two weeks. == Lab results (pdf) == A file is attached. Run: file report-0001 section-0002 ``` The report holds only what the dietitian shared with the patient. Private notes and the patient's own details are never part of it. ## 5. Download the file of a section For a section with `has_file: true`, call `GET /care/v1/report/{report_id}/section/{section_id}/file/get/document`. The answer is a small JSON object with a `url`. The link works for a short time only. The client reads that answer as it reads every other. The download itself is a plain request to that link. The link points to a file host, not to the Nurish'd API, so the program does not use the client for it. The client adds your API key to every request, and your key must never go to another host. The program uses the standard HTTP tool of each language instead: `requests`, `fetch` and `java.net.http`. The answer is the file's bytes, so the program writes them to disk. It names the file from its content type. Fetch the link when the person asks for the file. Do not store the link, and do not print or log it. Run the route again when you need the file again. ```python EXTENSIONS = { "application/pdf": ".pdf", "image/png": ".png", "image/jpeg": ".jpg", } def download_file(report_id, section_id): path = f"/care/v1/report/{report_id}/section/{section_id}/file/get/document" link = call("GET", path) # The link points to a file host, not to the API. Do not send your key to it. res = requests.get(link["url"], timeout=30) if not res.ok: sys.exit("The link did not work. Run this command again to get a new one.") kind = res.headers.get("Content-Type", "").split(";")[0] name = section_id + EXTENSIONS.get(kind, ".bin") Path(name).write_bytes(res.content) print(f"Saved {len(res.content)} bytes to {name}.") ``` ```javascript const EXTENSIONS = { 'application/pdf': '.pdf', 'image/png': '.png', 'image/jpeg': '.jpg', }; async function downloadFile(reportId, sectionId) { const path = `/care/v1/report/${reportId}/section/${sectionId}/file/get/document`; const link = await call('GET', path); // The link points to a file host, not to the API. Do not send your key to it. const res = await fetch(link.url); if (!res.ok) { exitWith( 'The link did not work. Run this command again to get a new one.', ); } const kind = (res.headers.get('content-type') ?? '').split(';')[0]; const name = sectionId + (EXTENSIONS[kind] ?? '.bin'); const bytes = Buffer.from(await res.arrayBuffer()); writeFileSync(name, bytes); console.log(`Saved ${bytes.length} bytes to ${name}.`); } ``` ```typescript const EXTENSIONS: Record = { 'application/pdf': '.pdf', 'image/png': '.png', 'image/jpeg': '.jpg', }; async function downloadFile(reportId: string, sectionId: string) { const path = `/care/v1/report/${reportId}/section/${sectionId}/file/get/document`; const link = await call<{ url: string }>('GET', path); // The link points to a file host, not to the API. Do not send your key to it. const res = await fetch(link.url); if (!res.ok) { exitWith( 'The link did not work. Run this command again to get a new one.', ); } const kind = (res.headers.get('content-type') ?? '').split(';')[0]; const name = sectionId + (EXTENSIONS[kind] ?? '.bin'); const bytes = Buffer.from(await res.arrayBuffer()); writeFileSync(name, bytes); console.log(`Saved ${bytes.length} bytes to ${name}.`); } ``` ```java static final Map EXTENSIONS = Map.of("application/pdf", ".pdf", "image/png", ".png", "image/jpeg", ".jpg"); static void downloadFile(String reportId, String sectionId) throws IOException, InterruptedException { String path = "/care/v1/report/%s/section/%s/file/get/document".formatted(reportId, sectionId); JsonNode link = Nurishd.call("GET", path); // The link points to a file host, not to the API. Do not send your key to it. HttpRequest request = HttpRequest.newBuilder(URI.create(link.path("url").asText())).build(); HttpResponse res = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofByteArray()); if (res.statusCode() != 200) { exitWith("The link did not work. Run this command again to get a new one."); } String kind = res.headers().firstValue("Content-Type").orElse("").split(";")[0]; String name = sectionId + EXTENSIONS.getOrDefault(kind, ".bin"); Files.write(Path.of(name), res.body()); System.out.println("Saved " + res.body().length + " bytes to " + name + "."); } ``` ```text python reports.py file report-0001 section-0002 Saved 15 bytes to section-0002.pdf. ``` ## 6. Keep the report private A report is health data. Show it only to the patient it belongs to, and to people your BAA allows. Do not log its contents or the file link. Log ids and the `request_id` instead. ## 7. Choose the command The last part reads the command line and runs one command. It catches an error answer and prints the status, the `code` and the `request_id`, then a hint. Branch on `code`, never on the message. ```python HINTS = { "scope_not_granted": "Your key lacks a scope, or your company has no signed BAA.", "test_mode_only": "This helper works with a Sandbox key only. Use a key that starts with nk-test-.", "booking_not_completable": "The booking was canceled or is already completed. Use a booking in status booked.", "connection_scope_not_granted": "The patient does not share reports. Connect the patient again and ask for care.reports.", "connection_not_active": "The patient revoked the connection. You can no longer read this patient's reports.", "not_found": "Nothing with this id is visible to your company. Check the id.", } def main(): args = sys.argv[1:] try: if len(args) == 2 and args[0] == "complete": complete_booking(args[1]) elif len(args) == 1 and args[0] == "events": list_events() elif args[:1] == ["list"] and len(args) in (1, 2): list_reports(args[1] if len(args) == 2 else None) elif len(args) == 2 and args[0] == "show": show_report(args[1]) elif len(args) == 3 and args[0] == "file": download_file(args[1], args[2]) else: print("Usage:") print(" python reports.py complete BOOKING_ID") print(" python reports.py events") print(" python reports.py list [BOOKING_ID]") print(" python reports.py show REPORT_ID") print(" python reports.py file REPORT_ID SECTION_ID") 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) ``` ```javascript const HINTS = { scope_not_granted: 'Your key lacks a scope, or your company has no signed BAA.', test_mode_only: 'This helper works with a Sandbox key only. Use a key that starts with nk-test-.', booking_not_completable: 'The booking was canceled or is already completed. Use a booking in status booked.', connection_scope_not_granted: 'The patient does not share reports. Connect the patient again and ask for care.reports.', connection_not_active: "The patient revoked the connection. You can no longer read this patient's reports.", not_found: 'Nothing with this id is visible to your company. Check the id.', }; async function main() { const args = process.argv.slice(2); try { if (args.length === 2 && args[0] === 'complete') { await completeBooking(args[1]); } else if (args.length === 1 && args[0] === 'events') { await listEvents(); } else if (args[0] === 'list' && args.length <= 2) { await listReports(args[1]); } else if (args.length === 2 && args[0] === 'show') { await showReport(args[1]); } else if (args.length === 3 && args[0] === 'file') { await downloadFile(args[1], args[2]); } else { console.log('Usage:'); console.log(' node reports.js complete BOOKING_ID'); console.log(' node reports.js events'); console.log(' node reports.js list [BOOKING_ID]'); console.log(' node reports.js show REPORT_ID'); console.log(' node reports.js file REPORT_ID SECTION_ID'); } } 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); } } ``` ```typescript const HINTS: Record = { scope_not_granted: 'Your key lacks a scope, or your company has no signed BAA.', test_mode_only: 'This helper works with a Sandbox key only. Use a key that starts with nk-test-.', booking_not_completable: 'The booking was canceled or is already completed. Use a booking in status booked.', connection_scope_not_granted: 'The patient does not share reports. Connect the patient again and ask for care.reports.', connection_not_active: "The patient revoked the connection. You can no longer read this patient's reports.", not_found: 'Nothing with this id is visible to your company. Check the id.', }; async function main() { const args = process.argv.slice(2); try { if (args.length === 2 && args[0] === 'complete') { await completeBooking(args[1]); } else if (args.length === 1 && args[0] === 'events') { await listEvents(); } else if (args[0] === 'list' && args.length <= 2) { await listReports(args[1]); } else if (args.length === 2 && args[0] === 'show') { await showReport(args[1]); } else if (args.length === 3 && args[0] === 'file') { await downloadFile(args[1], args[2]); } else { console.log('Usage:'); console.log(' node reports.js complete BOOKING_ID'); console.log(' node reports.js events'); console.log(' node reports.js list [BOOKING_ID]'); console.log(' node reports.js show REPORT_ID'); console.log(' node reports.js file REPORT_ID SECTION_ID'); } } 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); } } ``` ```java static final Map HINTS = Map.of( "scope_not_granted", "Your key lacks a scope, or your company has no signed BAA.", "test_mode_only", "This helper works with a Sandbox key only. Use a key that starts with nk-test-.", "booking_not_completable", "The booking was canceled or is already completed. Use a booking in status booked.", "connection_scope_not_granted", "The patient does not share reports. Connect the patient again and ask for care.reports.", "connection_not_active", "The patient revoked the connection. You can no longer read this patient's reports.", "not_found", "Nothing with this id is visible to your company. Check the id."); public static void main(String[] args) throws IOException, InterruptedException { try { if (args.length == 2 && args[0].equals("complete")) { completeBooking(args[1]); } else if (args.length == 1 && args[0].equals("events")) { listEvents(); } else if (args.length >= 1 && args.length <= 2 && args[0].equals("list")) { listReports(args.length == 2 ? args[1] : null); } else if (args.length == 2 && args[0].equals("show")) { showReport(args[1]); } else if (args.length == 3 && args[0].equals("file")) { downloadFile(args[1], args[2]); } else { System.out.println("Usage:"); System.out.println(" complete BOOKING_ID"); System.out.println(" events"); System.out.println(" list [BOOKING_ID]"); System.out.println(" show REPORT_ID"); System.out.println(" file REPORT_ID SECTION_ID"); } } 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 ```python # file: reports.py import sys from pathlib import Path import requests from nurishd import NurishdError, call EXTENSIONS = { "application/pdf": ".pdf", "image/png": ".png", "image/jpeg": ".jpg", } HINTS = { "scope_not_granted": "Your key lacks a scope, or your company has no signed BAA.", "test_mode_only": "This helper works with a Sandbox key only. Use a key that starts with nk-test-.", "booking_not_completable": "The booking was canceled or is already completed. Use a booking in status booked.", "connection_scope_not_granted": "The patient does not share reports. Connect the patient again and ask for care.reports.", "connection_not_active": "The patient revoked the connection. You can no longer read this patient's reports.", "not_found": "Nothing with this id is visible to your company. Check the id.", } def complete_booking(booking_id): path = f"/developer/v1/test-helper/booking/{booking_id}/complete/document" done = call("POST", path) print(f"Booking {done['booking_id']} is now {done['status']}.") print(f"A sample report was signed: {done['report_id']}") def list_events(): answer = call( "GET", "/developer/v1/event/query/documents", params={"type": "report.signed", "size": 10}, ) if not answer["data"]: print("No report.signed event yet. Wait a few seconds and run it again.") for event in answer["data"]: data = event["data"] print(f"{event['created']}: report {data['id']} for booking {data.get('booking')}") def list_reports(booking_id=None): params = {"booking": booking_id} if booking_id else {} answer = call("GET", "/care/v1/report/query/documents", params=params) if not answer["data"]: print("No signed report found.") for item in answer["data"]: print(f"{item['report_id']}: booking {item['booking_id']}, signed {item['signed_at']}") def show_report(report_id): report = call("GET", f"/care/v1/report/{report_id}/get/document") name = report["specialist_snapshot"].get("full_name", "unknown") print(f"Report {report['report_id']}, signed {report['signed_at']} by {name}") for section in sorted(report["sections"], key=lambda s: s["section_order"]): print() print(f"== {section['section_name']} ({section['section_type']}) ==") if section.get("section_content"): print(section["section_content"]) if section["has_file"]: print(f"A file is attached. Run: file {report_id} {section['section_id']}") def download_file(report_id, section_id): path = f"/care/v1/report/{report_id}/section/{section_id}/file/get/document" link = call("GET", path) # The link points to a file host, not to the API. Do not send your key to it. res = requests.get(link["url"], timeout=30) if not res.ok: sys.exit("The link did not work. Run this command again to get a new one.") kind = res.headers.get("Content-Type", "").split(";")[0] name = section_id + EXTENSIONS.get(kind, ".bin") Path(name).write_bytes(res.content) print(f"Saved {len(res.content)} bytes to {name}.") def main(): args = sys.argv[1:] try: if len(args) == 2 and args[0] == "complete": complete_booking(args[1]) elif len(args) == 1 and args[0] == "events": list_events() elif args[:1] == ["list"] and len(args) in (1, 2): list_reports(args[1] if len(args) == 2 else None) elif len(args) == 2 and args[0] == "show": show_report(args[1]) elif len(args) == 3 and args[0] == "file": download_file(args[1], args[2]) else: print("Usage:") print(" python reports.py complete BOOKING_ID") print(" python reports.py events") print(" python reports.py list [BOOKING_ID]") print(" python reports.py show REPORT_ID") print(" python reports.py file REPORT_ID SECTION_ID") 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() ``` ```javascript // file: reports.js import { writeFileSync } from 'node:fs'; import { NurishdError, call } from './nurishd.js'; const EXTENSIONS = { 'application/pdf': '.pdf', 'image/png': '.png', 'image/jpeg': '.jpg', }; const HINTS = { scope_not_granted: 'Your key lacks a scope, or your company has no signed BAA.', test_mode_only: 'This helper works with a Sandbox key only. Use a key that starts with nk-test-.', booking_not_completable: 'The booking was canceled or is already completed. Use a booking in status booked.', connection_scope_not_granted: 'The patient does not share reports. Connect the patient again and ask for care.reports.', connection_not_active: "The patient revoked the connection. You can no longer read this patient's reports.", not_found: 'Nothing with this id is visible to your company. Check the id.', }; function exitWith(message) { console.log(message); process.exit(1); } async function completeBooking(bookingId) { const path = `/developer/v1/test-helper/booking/${bookingId}/complete/document`; const done = await call('POST', path); console.log(`Booking ${done.booking_id} is now ${done.status}.`); console.log(`A sample report was signed: ${done.report_id}`); } async function listEvents() { const answer = await call('GET', '/developer/v1/event/query/documents', { params: { type: 'report.signed', size: 10 }, }); if (answer.data.length === 0) { console.log( 'No report.signed event yet. Wait a few seconds and run it again.', ); } for (const event of answer.data) { console.log( `${event.created}: report ${event.data.id} for booking ${event.data.booking}`, ); } } async function listReports(bookingId) { const params = bookingId ? { booking: bookingId } : {}; const answer = await call('GET', '/care/v1/report/query/documents', { params, }); if (answer.data.length === 0) console.log('No signed report found.'); for (const item of answer.data) { console.log( `${item.report_id}: booking ${item.booking_id}, signed ${item.signed_at}`, ); } } async function showReport(reportId) { const report = await call( 'GET', `/care/v1/report/${reportId}/get/document`, ); const name = report.specialist_snapshot.full_name ?? 'unknown'; console.log( `Report ${report.report_id}, signed ${report.signed_at} by ${name}`, ); const sections = [...report.sections].sort( (a, b) => a.section_order - b.section_order, ); for (const section of sections) { console.log(); console.log(`== ${section.section_name} (${section.section_type}) ==`); if (section.section_content) console.log(section.section_content); if (section.has_file) { console.log( `A file is attached. Run: file ${reportId} ${section.section_id}`, ); } } } async function downloadFile(reportId, sectionId) { const path = `/care/v1/report/${reportId}/section/${sectionId}/file/get/document`; const link = await call('GET', path); // The link points to a file host, not to the API. Do not send your key to it. const res = await fetch(link.url); if (!res.ok) { exitWith( 'The link did not work. Run this command again to get a new one.', ); } const kind = (res.headers.get('content-type') ?? '').split(';')[0]; const name = sectionId + (EXTENSIONS[kind] ?? '.bin'); const bytes = Buffer.from(await res.arrayBuffer()); writeFileSync(name, bytes); console.log(`Saved ${bytes.length} bytes to ${name}.`); } async function main() { const args = process.argv.slice(2); try { if (args.length === 2 && args[0] === 'complete') { await completeBooking(args[1]); } else if (args.length === 1 && args[0] === 'events') { await listEvents(); } else if (args[0] === 'list' && args.length <= 2) { await listReports(args[1]); } else if (args.length === 2 && args[0] === 'show') { await showReport(args[1]); } else if (args.length === 3 && args[0] === 'file') { await downloadFile(args[1], args[2]); } else { console.log('Usage:'); console.log(' node reports.js complete BOOKING_ID'); console.log(' node reports.js events'); console.log(' node reports.js list [BOOKING_ID]'); console.log(' node reports.js show REPORT_ID'); console.log(' node reports.js file REPORT_ID SECTION_ID'); } } 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(); ``` ```typescript // file: reports.ts import { writeFileSync } from 'node:fs'; import { NurishdError, call } from './nurishd.ts'; import type { Page } from './nurishd.ts'; interface Section { section_id: string; section_name: string; section_type: string; section_order: number; section_content?: string | null; has_file: boolean; } interface Report { report_id: string; signed_at: string; specialist_snapshot: { full_name?: string }; sections: Section[]; } interface ReportEvent { created: string; data: { id: string; booking?: string }; } interface ReportItem { report_id: string; booking_id: string; signed_at: string; } const EXTENSIONS: Record = { 'application/pdf': '.pdf', 'image/png': '.png', 'image/jpeg': '.jpg', }; const HINTS: Record = { scope_not_granted: 'Your key lacks a scope, or your company has no signed BAA.', test_mode_only: 'This helper works with a Sandbox key only. Use a key that starts with nk-test-.', booking_not_completable: 'The booking was canceled or is already completed. Use a booking in status booked.', connection_scope_not_granted: 'The patient does not share reports. Connect the patient again and ask for care.reports.', connection_not_active: "The patient revoked the connection. You can no longer read this patient's reports.", not_found: 'Nothing with this id is visible to your company. Check the id.', }; function exitWith(message: string): never { console.log(message); process.exit(1); } async function completeBooking(bookingId: string) { const path = `/developer/v1/test-helper/booking/${bookingId}/complete/document`; const done = await call<{ booking_id: string; report_id: string; status: string; }>('POST', path); console.log(`Booking ${done.booking_id} is now ${done.status}.`); console.log(`A sample report was signed: ${done.report_id}`); } async function listEvents() { const answer = await call>( 'GET', '/developer/v1/event/query/documents', { params: { type: 'report.signed', size: 10 } }, ); if (answer.data.length === 0) { console.log( 'No report.signed event yet. Wait a few seconds and run it again.', ); } for (const event of answer.data) { console.log( `${event.created}: report ${event.data.id} for booking ${event.data.booking}`, ); } } async function listReports(bookingId?: string) { const params: Record = bookingId ? { booking: bookingId } : {}; const answer = await call>( 'GET', '/care/v1/report/query/documents', { params }, ); if (answer.data.length === 0) console.log('No signed report found.'); for (const item of answer.data) { console.log( `${item.report_id}: booking ${item.booking_id}, signed ${item.signed_at}`, ); } } async function showReport(reportId: string) { const report = await call( 'GET', `/care/v1/report/${reportId}/get/document`, ); const name = report.specialist_snapshot.full_name ?? 'unknown'; console.log( `Report ${report.report_id}, signed ${report.signed_at} by ${name}`, ); const sections = [...report.sections].sort( (a, b) => a.section_order - b.section_order, ); for (const section of sections) { console.log(); console.log(`== ${section.section_name} (${section.section_type}) ==`); if (section.section_content) console.log(section.section_content); if (section.has_file) { console.log( `A file is attached. Run: file ${reportId} ${section.section_id}`, ); } } } async function downloadFile(reportId: string, sectionId: string) { const path = `/care/v1/report/${reportId}/section/${sectionId}/file/get/document`; const link = await call<{ url: string }>('GET', path); // The link points to a file host, not to the API. Do not send your key to it. const res = await fetch(link.url); if (!res.ok) { exitWith( 'The link did not work. Run this command again to get a new one.', ); } const kind = (res.headers.get('content-type') ?? '').split(';')[0]; const name = sectionId + (EXTENSIONS[kind] ?? '.bin'); const bytes = Buffer.from(await res.arrayBuffer()); writeFileSync(name, bytes); console.log(`Saved ${bytes.length} bytes to ${name}.`); } async function main() { const args = process.argv.slice(2); try { if (args.length === 2 && args[0] === 'complete') { await completeBooking(args[1]); } else if (args.length === 1 && args[0] === 'events') { await listEvents(); } else if (args[0] === 'list' && args.length <= 2) { await listReports(args[1]); } else if (args.length === 2 && args[0] === 'show') { await showReport(args[1]); } else if (args.length === 3 && args[0] === 'file') { await downloadFile(args[1], args[2]); } else { console.log('Usage:'); console.log(' node reports.js complete BOOKING_ID'); console.log(' node reports.js events'); console.log(' node reports.js list [BOOKING_ID]'); console.log(' node reports.js show REPORT_ID'); console.log(' node reports.js file REPORT_ID SECTION_ID'); } } 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(); ``` ```java // file: src/main/java/tutorial/Reports.java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import tutorial.Nurishd.NurishdException; public class Reports { static final Map EXTENSIONS = Map.of("application/pdf", ".pdf", "image/png", ".png", "image/jpeg", ".jpg"); static final Map HINTS = Map.of( "scope_not_granted", "Your key lacks a scope, or your company has no signed BAA.", "test_mode_only", "This helper works with a Sandbox key only. Use a key that starts with nk-test-.", "booking_not_completable", "The booking was canceled or is already completed. Use a booking in status booked.", "connection_scope_not_granted", "The patient does not share reports. Connect the patient again and ask for care.reports.", "connection_not_active", "The patient revoked the connection. You can no longer read this patient's reports.", "not_found", "Nothing with this id is visible to your company. Check the id."); static void exitWith(String message) { System.out.println(message); System.exit(1); } static void completeBooking(String bookingId) { String path = "/developer/v1/test-helper/booking/%s/complete/document".formatted(bookingId); JsonNode done = Nurishd.call("POST", path); System.out.println("Booking " + done.path("booking_id").asText() + " is now " + done.path("status").asText() + "."); System.out.println("A sample report was signed: " + done.path("report_id").asText()); } static void listEvents() { JsonNode answer = Nurishd.call( "GET", "/developer/v1/event/query/documents", Map.of("type", "report.signed", "size", 10), null); if (answer.path("data").isEmpty()) { System.out.println("No report.signed event yet. Wait a few seconds and run it again."); } for (JsonNode event : answer.path("data")) { System.out.println(event.path("created").asText() + ": report " + event.path("data").path("id").asText() + " for booking " + event.path("data").path("booking").asText()); } } static void listReports(String bookingId) { Map params = bookingId == null ? Map.of() : Map.of("booking", bookingId); JsonNode answer = Nurishd.call("GET", "/care/v1/report/query/documents", params, null); if (answer.path("data").isEmpty()) { System.out.println("No signed report found."); } for (JsonNode item : answer.path("data")) { System.out.println(item.path("report_id").asText() + ": booking " + item.path("booking_id").asText() + ", signed " + item.path("signed_at").asText()); } } static void showReport(String reportId) { JsonNode report = Nurishd.call("GET", "/care/v1/report/%s/get/document".formatted(reportId)); String name = report.path("specialist_snapshot").path("full_name").asText("unknown"); System.out.println("Report " + report.path("report_id").asText() + ", signed " + report.path("signed_at").asText() + " by " + name); List sections = new ArrayList<>(); report.path("sections").forEach(sections::add); sections.sort(Comparator.comparingInt(s -> s.path("section_order").asInt())); for (JsonNode section : sections) { System.out.println(); System.out.println("== " + section.path("section_name").asText() + " (" + section.path("section_type").asText() + ") =="); if (!section.path("section_content").asText("").isEmpty()) { System.out.println(section.path("section_content").asText()); } if (section.path("has_file").asBoolean()) { System.out.println("A file is attached. Run: file " + reportId + " " + section.path("section_id").asText()); } } } static void downloadFile(String reportId, String sectionId) throws IOException, InterruptedException { String path = "/care/v1/report/%s/section/%s/file/get/document".formatted(reportId, sectionId); JsonNode link = Nurishd.call("GET", path); // The link points to a file host, not to the API. Do not send your key to it. HttpRequest request = HttpRequest.newBuilder(URI.create(link.path("url").asText())).build(); HttpResponse res = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofByteArray()); if (res.statusCode() != 200) { exitWith("The link did not work. Run this command again to get a new one."); } String kind = res.headers().firstValue("Content-Type").orElse("").split(";")[0]; String name = sectionId + EXTENSIONS.getOrDefault(kind, ".bin"); Files.write(Path.of(name), res.body()); System.out.println("Saved " + res.body().length + " bytes to " + name + "."); } public static void main(String[] args) throws IOException, InterruptedException { try { if (args.length == 2 && args[0].equals("complete")) { completeBooking(args[1]); } else if (args.length == 1 && args[0].equals("events")) { listEvents(); } else if (args.length >= 1 && args.length <= 2 && args[0].equals("list")) { listReports(args.length == 2 ? args[1] : null); } else if (args.length == 2 && args[0].equals("show")) { showReport(args[1]); } else if (args.length == 3 && args[0].equals("file")) { downloadFile(args[1], args[2]); } else { System.out.println("Usage:"); System.out.println(" complete BOOKING_ID"); System.out.println(" events"); System.out.println(" list [BOOKING_ID]"); System.out.println(" show REPORT_ID"); System.out.println(" file REPORT_ID SECTION_ID"); } } 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 `report:read` (or `booking:write` for the helper), or no BAA. | Use a key with the scopes. See [Scopes](/docs/concepts/scopes) and [BAA handling](/docs/care/baa). | | `403 connection_scope_not_granted` | The patient did not allow `care.reports`. | Create the patient again with a key that holds `report:read`. Send the new link. | | `403 test_mode_only` | You called the test helper with a Production key. | Use a Sandbox key. Production has no helper. | | `404 not_found` | The report does not exist, or the visit was booked by the patient or by another company. Also a section that was not shared or has no file. For the helper: the booking was not made by your company with a Sandbox key. | Check the id. | | `409 connection_not_active` | The patient revoked the connection. | You can no longer read this patient's reports. Connect the patient again. | | `409 booking_not_completable` | The booking was canceled or is already completed. | Book another visit and complete that one. | | `422 validation_error` | A parameter is invalid, such as a `size` over 50. | Fix the parameter. | | An empty list | The report is not signed yet, or the patient's connection is no longer active. | In the Sandbox, run `complete` first. | | `The link did not work` | The short-lived link expired. | Run the `file` command again. It asks for a new link. | ## Next - [Visit reports](/docs/care/reports): every field and error of the report routes. - [Events](/docs/events/events): the `report.signed` event and the other types. - [BAA handling](/docs/care/baa): what care data needs. - [Receive order webhooks](/docs/tutorials/receive-order-webhooks): receive events on your server. --- # Use Nurish'd with a Shopify store Build a small server that your Shopify store reaches through an app proxy, to connect shoppers to Nurish'd, list meals for their address and place meal orders. Nurish'd has no Shopify app or plugin. You build the bridge yourself: one small server of your own that calls the Nurish'd API, reached from your store through a Shopify app proxy. When it runs, a shopper who is signed in to your store connects their Nurish'd account, sees the meals that can be delivered to their address, and places a meal order. ## What this does and does not do - It connects a shopper of your store to Nurish'd, lists meals for the shopper's default Shopify address, and places Nurish'd meal orders for them. - A Nurish'd meal order is not a Shopify order. It does not go through Shopify checkout, and Shopify takes no payment for it. - The shopper pays Nurish'd for the meals in the browser with Stripe.js, using the payment intent that the order answer carries. See [Orders](/docs/meals/orders). The Nurish'd API has no way to take the payment through Shopify checkout. - Your Nurish'd API key stays on your server. It never goes into theme code, a Liquid template or the browser. ## How the pieces fit An app proxy is a Shopify feature. Shopify takes requests for one path on your store's domain and forwards them to your server. See [About app proxies](https://shopify.dev/docs/apps/build/online-store/app-proxies). The Admin API is Shopify's API for reading store data, such as a customer. ```text Shopper's browser GET https://shop.example.com/apps/nurishd/meals | Shopify app proxy: adds who the shopper is, then signs the request GET https://your-server.example.com/proxy/meals?logged_in_customer_id=...&signature=... | Your server: checks the signature, reads the customer from the Shopify Admin API, calls the Nurish'd API with your key ``` The shopper only ever talks to your store's domain. Your server is the only place that holds your Nurish'd key and your Shopify secrets. ## Before you start - You finished [Set up your project](/docs/tutorials/set-up-your-project). Your project has the `nurishd` client file and a Sandbox key in `NURISHD_API_KEY`. - Your key has the scopes `catalog:read`, `order:read` and `order:write`. Run `check_key` from the setup tutorial to see your scopes. - You know the connect flow from [Connect a customer](/docs/tutorials/connect-a-customer). This tutorial uses it without explaining it again. - You have a Shopify store and you can create apps in the [Dev Dashboard](https://shopify.dev/docs/apps/build/dev-dashboard/create-apps-using-dev-dashboard). The app and the store must be in the same Shopify organization. Step 1 says why. - Your server needs a public HTTPS address, because Shopify must reach it. While you build, use a tunnel tool, as in [Receive order webhooks](/docs/tutorials/receive-order-webhooks). - Install the web server package for your language. | Language | Command | | ---------- | ------------------------------------------------------------------------ | | Python | `pip install flask` | | JavaScript | `npm install express` | | TypeScript | `npm install express` and `npm install --save-dev @types/express` | | Java | Replace `pom.xml` with the one below. It adds Javalin and a log package. | Java only. This `pom.xml` is the one from the setup tutorial plus two dependencies. Javalin is the web server and `slf4j-simple` prints its logs. ```xml 4.0.0 com.example nurishd-tutorial 1.0.0 17 UTF-8 com.fasterxml.jackson.core jackson-databind 2.17.2 io.javalin javalin 6.3.0 org.slf4j slf4j-simple 2.0.16 org.codehaus.mojo exec-maven-plugin 3.4.1 ``` ## 1. Create the Shopify app Your server talks to Shopify as an app. Create it in the Dev Dashboard. These steps follow [Create apps using the Dev Dashboard](https://shopify.dev/docs/apps/build/dev-dashboard/create-apps-using-dev-dashboard) and [About app proxies](https://shopify.dev/docs/apps/build/online-store/app-proxies). 1. In the [Dev Dashboard](https://dev.shopify.com/dashboard/), open **Apps**, select **Create app**, then **Start from Dev Dashboard**. Name the app and select **Create**. 2. Open **Versions** and create a version. For **App URL**, keep `https://shopify.dev/apps/default-app-home`: this app has no page inside the Shopify admin. 3. Under **Scopes**, add `read_customers` and `write_app_proxy`. `read_customers` lets your server read a customer. `write_app_proxy` is needed to set up an app proxy. 4. Under **App proxy**, set the prefix to `apps`, the subpath to `nurishd`, and the proxy URL to `https://your-server.example.com/proxy`. Then select **Release**. 5. Select **Install app** and install the app on your store. 6. Open **Settings** and copy the **Client ID** and the **Client secret**. With this proxy, `https://shop.example.com/apps/nurishd/connect` goes to `https://your-server.example.com/proxy/connect`. A store owner can change the prefix and subpath in the Shopify admin. If they do, the store URLs in this tutorial change too, and you register the new return URL. Your server reads a customer's name, email and address. Shopify calls this protected customer data and has rules for it. In development, you select the data and the fields you use. In the Dev Dashboard, open your app's **Settings**, then **Access requests**, and next to **Protected customer data** select **Manage**. Select **Customer data** and the fields **Name**, **Email** and **Address**, give your reasons, and save. The steps and Shopify's rules for this data are in [Protected customer data](https://shopify.dev/docs/apps/launch/protected-customer-data). A field your app may not read comes back empty, with an error that names it. Your server gets its Admin API access token from the Client ID and the Client secret. Shopify calls this the client credentials grant. It works only when the app and the store are in the same Shopify organization, and each token lasts 24 hours. See [Authenticate an app for stores in your organization](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant). For a store of another organization, Shopify has other ways to get a token, listed in [About app authentication](https://shopify.dev/docs/apps/build/authentication-authorization). Last, register the return URL in the Nurish'd console. A return URL is where Nurish'd sends the shopper after they approve. Open **Settings**, find **Return URLs**, and add `https://shop.example.com/apps/nurishd/return` with your store's own domain. See [Company settings](/docs/console/company-settings). Put the Shopify values and the return URL in variables, next to `NURISHD_API_KEY`. `SHOPIFY_SHOP` is your store's `myshopify.com` domain. macOS and Linux: ```bash export SHOPIFY_SHOP="your-store.myshopify.com" export SHOPIFY_CLIENT_ID="your-client-id" export SHOPIFY_CLIENT_SECRET="your-client-secret" export RETURN_URL="https://shop.example.com/apps/nurishd/return" ``` Windows PowerShell: ```powershell $env:SHOPIFY_SHOP = "your-store.myshopify.com" $env:SHOPIFY_CLIENT_ID = "your-client-id" $env:SHOPIFY_CLIENT_SECRET = "your-client-secret" $env:RETURN_URL = "https://shop.example.com/apps/nurishd/return" ``` The client secret is a password for your app. Keep it on your server, like your Nurish'd key. ## 2. Check the proxy signature Shopify adds these query parameters to every request it forwards. See [Authenticate app proxies](https://shopify.dev/docs/apps/build/online-store/app-proxies/authenticate-app-proxies). | Parameter | What it holds | | ----------------------- | --------------------------------------------------------------------- | | `shop` | The store's `myshopify.com` domain. | | `path_prefix` | The store path that was forwarded, such as `/apps/nurishd`. | | `timestamp` | A time in seconds since 1 January 1970, UTC. | | `logged_in_customer_id` | The id of the shopper who is signed in to the store. Empty when none. | | `signature` | A signature of all the other parameters, made with your app's secret. | Your server must refuse a request whose signature does not verify. Your server's address is public, so anyone can call it. Without the check, anyone could add `logged_in_customer_id` to the address and act as any customer of your store. Shopify makes the signature like this, and your server does the same and compares: 1. Read the query string as it arrived and decode each value. Take out `signature`. 2. Write each parameter as `name=value`. A parameter that appears more than once is written once, with its values joined by commas: `extra=1&extra=2` becomes `extra=1,2`. 3. Sort these pieces and join them with nothing between them. 4. Compute the HMAC-SHA256 of that text with your app's client secret as the key, written as hex. 5. Compare it with `signature`. Use a constant-time comparison, which takes the same time whether the values match or not, so an attacker learns nothing from the timing. The code reads the raw query string itself. A framework's own query parser can drop empty values or merge repeated ones, and then the signature no longer matches. The check runs before every route. ```python def proxy_signature_ok(query_string): """Checks the signature Shopify adds to every app proxy request.""" values = {} signature = "" for name, value in parse_qsl(query_string, keep_blank_values=True): if name == "signature": signature = value else: values.setdefault(name, []).append(value) message = "".join( sorted(f"{name}={','.join(items)}" for name, items in values.items()) ) expected = hmac.new( SHOPIFY_CLIENT_SECRET.encode(), message.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature) @app.before_request def check_signature(): if not proxy_signature_ok(request.query_string.decode()): abort(401) ``` ```javascript /** Checks the signature Shopify adds to every app proxy request. */ function proxySignatureOk(queryString) { const values = new Map(); let signature = ''; for (const [name, value] of new URLSearchParams(queryString)) { if (name === 'signature') signature = value; else values.set(name, [...(values.get(name) ?? []), value]); } const message = [...values] .map(([name, items]) => `${name}=${items.join(',')}`) .sort() .join(''); const expected = crypto .createHmac('sha256', SHOPIFY_CLIENT_SECRET) .update(message) .digest('hex'); return ( signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)) ); } app.use((req, res, next) => { const queryString = req.originalUrl.split('?')[1] ?? ''; if (!proxySignatureOk(queryString)) return res.sendStatus(401); next(); }); ``` ```typescript /** Checks the signature Shopify adds to every app proxy request. */ function proxySignatureOk(queryString: string): boolean { const values = new Map(); let signature = ''; for (const [name, value] of new URLSearchParams(queryString)) { if (name === 'signature') signature = value; else values.set(name, [...(values.get(name) ?? []), value]); } const message = [...values] .map(([name, items]) => `${name}=${items.join(',')}`) .sort() .join(''); const expected = crypto .createHmac('sha256', SHOPIFY_CLIENT_SECRET) .update(message) .digest('hex'); return ( signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)) ); } app.use((req, res, next) => { const queryString = req.originalUrl.split('?')[1] ?? ''; if (!proxySignatureOk(queryString)) return res.sendStatus(401); next(); }); ``` ```java /** Checks the signature Shopify adds to every app proxy request. */ static boolean proxySignatureOk(String queryString) throws Exception { Map> values = new HashMap<>(); String signature = ""; for (String pair : (queryString == null ? "" : queryString).split("&")) { if (pair.isEmpty()) continue; String[] parts = pair.split("=", 2); String name = URLDecoder.decode(parts[0], StandardCharsets.UTF_8); String value = parts.length > 1 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : ""; if (name.equals("signature")) signature = value; else values.computeIfAbsent(name, key -> new ArrayList<>()).add(value); } List pieces = new ArrayList<>(); values.forEach((name, items) -> pieces.add(name + "=" + String.join(",", items))); pieces.sort(null); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(SHOPIFY_CLIENT_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); String expected = HexFormat.of() .formatHex(mac.doFinal(String.join("", pieces).getBytes(StandardCharsets.UTF_8))); return MessageDigest.isEqual( expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8)); } app.before(ctx -> { if (!proxySignatureOk(ctx.queryString())) throw new UnauthorizedResponse(); }); ``` A valid signature proves the request came through Shopify unchanged. It does not prove the shopper may see the data they ask for. Shopify's doc asks you to check that too. This server only ever reads data of the shopper in `logged_in_customer_id`. ## 3. Know who the shopper is `logged_in_customer_id` is the Shopify id of the signed-in shopper. When it is empty, the shopper is not signed in to the store, and your server answers with a short page that links to the store's sign-in. A proxy answer with the content type `application/liquid` is shown inside your store's theme. Shopify also fills in any Liquid in it. Liquid is Shopify's template language, and `{{ routes.account_login_url }}` is the store's sign-in address. See [App proxies: Liquid response](https://shopify.dev/docs/apps/build/online-store/app-proxies#liquid-response) and [routes](https://shopify.dev/docs/api/liquid/objects/routes). ```python def page(html): """A page Shopify shows inside the store's theme.""" return Response(html, content_type="application/liquid") def sign_in_page(): """Asks the shopper to sign in. Shopify fills in the sign-in link.""" return page( "

Sign in to the store first.

" '

Sign in

' ) ``` ```javascript /** A page Shopify shows inside the store's theme. */ function page(res, html) { res.type('application/liquid').end(html); } /** Asks the shopper to sign in. Shopify fills in the sign-in link. */ function signInPage(res) { page( res, '

Sign in to the store first.

Sign in

', ); } ``` ```typescript /** A page Shopify shows inside the store's theme. */ function page(res: Response, html: string) { res.type('application/liquid').end(html); } /** Asks the shopper to sign in. Shopify fills in the sign-in link. */ function signInPage(res: Response) { page( res, '

Sign in to the store first.

Sign in

', ); } ``` ```java /** A page Shopify shows inside the store's theme. */ static void page(Context ctx, String html) { ctx.contentType("application/liquid").result(html); } /** Asks the shopper to sign in. Shopify fills in the sign-in link. */ static void signInPage(Context ctx) { page(ctx, "

Sign in to the store first.

" + "

Sign in

"); } ``` Nurish'd knows each customer by an `external_id`, an id of your own. Here it is `shopify-` followed by the Shopify customer id, for example `shopify-1001`. The Shopify id never changes for that shopper, so the same person always gets the same `external_id`. That matters: Nurish'd accepts one `external_id` per person and refuses a second one for the same email. See [Connections](/docs/concepts/connections#one-external-id-per-person). ## 4. Read the customer from Shopify Two small functions talk to Shopify. `shopify_token` gets an Admin API access token and keeps it until shortly before it expires. `shopify_customer` asks the GraphQL Admin API for the customer's name, email and default address. GraphQL is a query language: you list the fields you want and get only those. The Admin API has dated versions, such as `2026-10`, and a new one comes out every three months. Put the version you use in `SHOPIFY_API_VERSION`. See [API versioning](https://shopify.dev/docs/api/usage/versioning). The query uses the [customer](https://shopify.dev/docs/api/admin-graphql/latest/queries/customer) query, which needs the `read_customers` scope. `SHOPIFY_URL` is for local tests only. Leave it unset and the code calls your store. ```python SHOPIFY_SHOP = os.environ["SHOPIFY_SHOP"] SHOPIFY_CLIENT_ID = os.environ["SHOPIFY_CLIENT_ID"] SHOPIFY_CLIENT_SECRET = os.environ["SHOPIFY_CLIENT_SECRET"] SHOPIFY_API_VERSION = "2026-10" # For local tests only: send the Shopify calls to a fake server. SHOPIFY_URL = os.environ.get("SHOPIFY_URL", f"https://{SHOPIFY_SHOP}") RETURN_URL = os.environ["RETURN_URL"] def shopify_token(): """Gets an Admin API access token. Shopify's tokens last 24 hours.""" if time.time() < token["expires_at"] - 60: return token["value"] res = requests.post( f"{SHOPIFY_URL}/admin/oauth/access_token", data={ "grant_type": "client_credentials", "client_id": SHOPIFY_CLIENT_ID, "client_secret": SHOPIFY_CLIENT_SECRET, }, timeout=30, ) res.raise_for_status() answer = res.json() token["value"] = answer["access_token"] token["expires_at"] = time.time() + answer["expires_in"] return token["value"] def shopify_customer(customer_id): """Reads a customer's name, email and default address from Shopify.""" query = """ query ($id: ID!) { customer(id: $id) { firstName lastName defaultEmailAddress { emailAddress } defaultAddress { address1 address2 city provinceCode countryCodeV2 zip } } }""" res = requests.post( f"{SHOPIFY_URL}/admin/api/{SHOPIFY_API_VERSION}/graphql.json", headers={"X-Shopify-Access-Token": shopify_token()}, json={ "query": query, "variables": {"id": f"gid://shopify/Customer/{customer_id}"}, }, timeout=30, ) res.raise_for_status() answer = res.json() if answer.get("errors"): raise RuntimeError(f"Shopify said: {answer['errors']}") return answer["data"]["customer"] ``` ```javascript const SHOPIFY_SHOP = process.env.SHOPIFY_SHOP; const SHOPIFY_CLIENT_ID = process.env.SHOPIFY_CLIENT_ID; const SHOPIFY_CLIENT_SECRET = process.env.SHOPIFY_CLIENT_SECRET; const SHOPIFY_API_VERSION = '2026-10'; // For local tests only: send the Shopify calls to a fake server. const SHOPIFY_URL = process.env.SHOPIFY_URL ?? `https://${SHOPIFY_SHOP}`; const RETURN_URL = process.env.RETURN_URL; /** Gets an Admin API access token. Shopify's tokens last 24 hours. */ async function shopifyToken() { if (Date.now() < token.expiresAt - 60_000) return token.value; const res = await fetch(`${SHOPIFY_URL}/admin/oauth/access_token`, { method: 'POST', body: new URLSearchParams({ grant_type: 'client_credentials', client_id: SHOPIFY_CLIENT_ID, client_secret: SHOPIFY_CLIENT_SECRET, }), }); if (!res.ok) throw new Error(`Shopify token: ${res.status}`); const answer = await res.json(); token.value = answer.access_token; token.expiresAt = Date.now() + answer.expires_in * 1000; return token.value; } /** Reads a customer's name, email and default address from Shopify. */ async function shopifyCustomer(customerId) { const query = ` query ($id: ID!) { customer(id: $id) { firstName lastName defaultEmailAddress { emailAddress } defaultAddress { address1 address2 city provinceCode countryCodeV2 zip } } }`; const res = await fetch( `${SHOPIFY_URL}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Shopify-Access-Token': await shopifyToken(), }, body: JSON.stringify({ query, variables: { id: `gid://shopify/Customer/${customerId}` }, }), }, ); if (!res.ok) throw new Error(`Shopify customer: ${res.status}`); const answer = await res.json(); if (answer.errors) throw new Error(`Shopify said: ${JSON.stringify(answer.errors)}`); return answer.data.customer; } ``` ```typescript const SHOPIFY_SHOP = process.env.SHOPIFY_SHOP ?? ''; const SHOPIFY_CLIENT_ID = process.env.SHOPIFY_CLIENT_ID ?? ''; const SHOPIFY_CLIENT_SECRET = process.env.SHOPIFY_CLIENT_SECRET ?? ''; const SHOPIFY_API_VERSION = '2026-10'; // For local tests only: send the Shopify calls to a fake server. const SHOPIFY_URL = process.env.SHOPIFY_URL ?? `https://${SHOPIFY_SHOP}`; const RETURN_URL = process.env.RETURN_URL ?? ''; /** Gets an Admin API access token. Shopify's tokens last 24 hours. */ async function shopifyToken(): Promise { if (Date.now() < token.expiresAt - 60_000) return token.value; const res = await fetch(`${SHOPIFY_URL}/admin/oauth/access_token`, { method: 'POST', body: new URLSearchParams({ grant_type: 'client_credentials', client_id: SHOPIFY_CLIENT_ID, client_secret: SHOPIFY_CLIENT_SECRET, }), }); if (!res.ok) throw new Error(`Shopify token: ${res.status}`); const answer = (await res.json()) as { access_token: string; expires_in: number; }; token.value = answer.access_token; token.expiresAt = Date.now() + answer.expires_in * 1000; return token.value; } /** Reads a customer's name, email and default address from Shopify. */ async function shopifyCustomer(customerId: string): Promise { const query = ` query ($id: ID!) { customer(id: $id) { firstName lastName defaultEmailAddress { emailAddress } defaultAddress { address1 address2 city provinceCode countryCodeV2 zip } } }`; const res = await fetch( `${SHOPIFY_URL}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Shopify-Access-Token': await shopifyToken(), }, body: JSON.stringify({ query, variables: { id: `gid://shopify/Customer/${customerId}` }, }), }, ); if (!res.ok) throw new Error(`Shopify customer: ${res.status}`); const answer = (await res.json()) as { data: { customer: ShopifyCustomer }; errors?: unknown; }; if (answer.errors) throw new Error(`Shopify said: ${JSON.stringify(answer.errors)}`); return answer.data.customer; } ``` ```java static final String SHOPIFY_SHOP = System.getenv("SHOPIFY_SHOP"); static final String SHOPIFY_CLIENT_ID = System.getenv("SHOPIFY_CLIENT_ID"); static final String SHOPIFY_CLIENT_SECRET = System.getenv("SHOPIFY_CLIENT_SECRET"); static final String SHOPIFY_API_VERSION = "2026-10"; // For local tests only: send the Shopify calls to a fake server. static final String SHOPIFY_URL = System.getenv().getOrDefault("SHOPIFY_URL", "https://" + SHOPIFY_SHOP); static final String RETURN_URL = System.getenv("RETURN_URL"); static final HttpClient HTTP = HttpClient.newHttpClient(); /** Gets an Admin API access token. Shopify's tokens last 24 hours. */ static synchronized String shopifyToken() throws Exception { if (System.currentTimeMillis() < tokenExpiresAt - 60_000) return token; String form = "grant_type=client_credentials" + "&client_id=" + URLEncoder.encode(SHOPIFY_CLIENT_ID, StandardCharsets.UTF_8) + "&client_secret=" + URLEncoder.encode(SHOPIFY_CLIENT_SECRET, StandardCharsets.UTF_8); HttpRequest request = HttpRequest.newBuilder(URI.create(SHOPIFY_URL + "/admin/oauth/access_token")) .header("Content-Type", "application/x-www-form-urlencoded") .POST(HttpRequest.BodyPublishers.ofString(form)) .build(); HttpResponse res = HTTP.send(request, HttpResponse.BodyHandlers.ofString()); if (res.statusCode() != 200) throw new IllegalStateException("Shopify token: " + res.statusCode()); JsonNode answer = Nurishd.JSON.readTree(res.body()); token = answer.path("access_token").asText(); tokenExpiresAt = System.currentTimeMillis() + answer.path("expires_in").asLong() * 1000; return token; } /** Reads a customer's name, email and default address from Shopify. */ static JsonNode shopifyCustomer(String customerId) throws Exception { String query = """ query ($id: ID!) { customer(id: $id) { firstName lastName defaultEmailAddress { emailAddress } defaultAddress { address1 address2 city provinceCode countryCodeV2 zip } } }"""; String body = Nurishd.JSON.writeValueAsString(Map.of( "query", query, "variables", Map.of("id", "gid://shopify/Customer/" + customerId))); HttpRequest request = HttpRequest.newBuilder( URI.create(SHOPIFY_URL + "/admin/api/" + SHOPIFY_API_VERSION + "/graphql.json")) .header("Content-Type", "application/json") .header("X-Shopify-Access-Token", shopifyToken()) .POST(HttpRequest.BodyPublishers.ofString(body)) .build(); HttpResponse res = HTTP.send(request, HttpResponse.BodyHandlers.ofString()); if (res.statusCode() != 200) throw new IllegalStateException("Shopify customer: " + res.statusCode()); JsonNode answer = Nurishd.JSON.readTree(res.body()); if (answer.has("errors")) throw new IllegalStateException("Shopify said: " + answer.get("errors")); return answer.path("data").path("customer"); } ``` ## 5. Connect the shopper `GET /apps/nurishd/connect` reads the shopper from Shopify and creates the Nurish'd customer with `POST /meals/v1/customer/create/document`. The `return_url` is your store's return route. The answer holds the `connect_url`, the Nurish'd page where the shopper approves. The shopper must open the Nurish'd page as a full page, never in a frame. Shopify's doc says it follows 30x redirects in a proxy answer, so a redirect may not reach the browser as a redirect. The route answers with a short page and a link instead. The shopper selects the link and the browser opens the Nurish'd page itself. ```python @app.get("/proxy/connect") def connect(): customer_id = request.args.get("logged_in_customer_id", "") if not customer_id: return sign_in_page() shopper = shopify_customer(customer_id) try: created = call( "POST", "/meals/v1/customer/create/document", body={ "external_id": f"shopify-{customer_id}", "email": shopper["defaultEmailAddress"]["emailAddress"], "first_name": shopper["firstName"], "last_name": shopper["lastName"], "return_url": RETURN_URL, }, ) except NurishdError as error: if error.code == "person_already_connected": return page("

This email is already connected under another store account.

") raise if created["connection"]["status"] == "active": connected[customer_id] = created["user"] return page("

Your Nurish'd account is already connected.

") return page( "

Nurish'd asks you to approve the connection on its own page.

" f'

Continue to Nurish\'d

' ) ``` ```javascript app.get('/proxy/connect', async (req, res) => { const customerId = req.query.logged_in_customer_id ?? ''; if (!customerId) return signInPage(res); const shopper = await shopifyCustomer(customerId); let created; try { created = await call('POST', '/meals/v1/customer/create/document', { body: { external_id: `shopify-${customerId}`, email: shopper.defaultEmailAddress.emailAddress, first_name: shopper.firstName, last_name: shopper.lastName, return_url: RETURN_URL, }, }); } catch (error) { if ( error instanceof NurishdError && error.code === 'person_already_connected' ) { return page( res, '

This email is already connected under another store account.

', ); } throw error; } if (created.connection.status === 'active') { connected.set(customerId, created.user); return page(res, "

Your Nurish'd account is already connected.

"); } page( res, "

Nurish'd asks you to approve the connection on its own page.

" + `

Continue to Nurish'd

`, ); }); ``` ```typescript app.get('/proxy/connect', async (req, res) => { const customerId = String(req.query.logged_in_customer_id ?? ''); if (!customerId) return signInPage(res); const shopper = await shopifyCustomer(customerId); let created: CreatedCustomer; try { created = await call( 'POST', '/meals/v1/customer/create/document', { body: { external_id: `shopify-${customerId}`, email: shopper.defaultEmailAddress.emailAddress, first_name: shopper.firstName, last_name: shopper.lastName, return_url: RETURN_URL, }, }, ); } catch (error) { if ( error instanceof NurishdError && error.code === 'person_already_connected' ) { return page( res, '

This email is already connected under another store account.

', ); } throw error; } if (created.connection.status === 'active') { connected.set(customerId, created.user); return page(res, "

Your Nurish'd account is already connected.

"); } page( res, "

Nurish'd asks you to approve the connection on its own page.

" + `

Continue to Nurish'd

`, ); }); ``` ```java static void connect(Context ctx) throws Exception { String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault(""); if (customerId.isEmpty()) { signInPage(ctx); return; } JsonNode shopper = shopifyCustomer(customerId); JsonNode created; try { created = Nurishd.call("POST", "/meals/v1/customer/create/document", Map.of(), Map.of( "external_id", "shopify-" + customerId, "email", shopper.path("defaultEmailAddress").path("emailAddress").asText(), "first_name", shopper.path("firstName").asText(), "last_name", shopper.path("lastName").asText(), "return_url", RETURN_URL)); } catch (Nurishd.NurishdException error) { if (!error.code.equals("person_already_connected")) throw error; page(ctx, "

This email is already connected under another store account.

"); return; } if (created.path("connection").path("status").asText().equals("active")) { connected.put(customerId, created.path("user").asText()); page(ctx, "

Your Nurish'd account is already connected.

"); return; } page(ctx, "

Nurish'd asks you to approve the connection on its own page.

" + "

Continue to Nurish'd

"); } ``` When the email is already connected under another `external_id`, create answers `409 person_already_connected` and the route says so. When the connection is already `active`, there is nothing to approve and the route says the account is connected. ## 6. Handle the return After the shopper decides, Nurish'd sends them to your return URL with `connection_id` and `status` in the query. The shopper lands on your store, so the request comes through the proxy and is signed like any other. Never trust the `status` in the address: anyone can edit it. The route reads the connection with `GET /meals/v1/connection/{connection_id}/get/document`, checks that its `external_id` belongs to this shopper, and checks that it is `active`. Then it remembers the Nurish'd customer id for the Shopify customer. This tutorial keeps that in memory, so a restart forgets it. A real app keeps it in its own database. ```python # Shopify customer id -> Nurish'd customer id. A real app keeps this in its database. connected = {} ``` ```javascript // Shopify customer id -> Nurish'd customer id. A real app keeps this in its database. const connected = new Map(); ``` ```typescript // Shopify customer id -> Nurish'd customer id. A real app keeps this in its database. const connected = new Map(); ``` ```java // Shopify customer id -> Nurish'd customer id. A real app keeps this in its database. static final Map connected = new HashMap<>(); ``` The return route: ```python @app.get("/proxy/return") def returned(): customer_id = request.args.get("logged_in_customer_id", "") if not customer_id: return sign_in_page() connection_id = request.args.get("connection_id", "") connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document") if connection["external_id"] != f"shopify-{customer_id}": abort(403) if connection["status"] != "active": return page("

The connection was not approved.

") connected[customer_id] = connection["user"] return page("

Your Nurish'd account is connected.

") ``` ```javascript app.get('/proxy/return', async (req, res) => { const customerId = req.query.logged_in_customer_id ?? ''; if (!customerId) return signInPage(res); const connectionId = req.query.connection_id ?? ''; const connection = await call( 'GET', `/meals/v1/connection/${connectionId}/get/document`, ); if (connection.external_id !== `shopify-${customerId}`) return res.sendStatus(403); if (connection.status !== 'active') return page(res, '

The connection was not approved.

'); connected.set(customerId, connection.user); page(res, "

Your Nurish'd account is connected.

"); }); ``` ```typescript app.get('/proxy/return', async (req, res) => { const customerId = String(req.query.logged_in_customer_id ?? ''); if (!customerId) return signInPage(res); const connectionId = String(req.query.connection_id ?? ''); const connection = await call( 'GET', `/meals/v1/connection/${connectionId}/get/document`, ); if (connection.external_id !== `shopify-${customerId}`) return res.sendStatus(403); if (connection.status !== 'active') return page(res, '

The connection was not approved.

'); connected.set(customerId, connection.user); page(res, "

Your Nurish'd account is connected.

"); }); ``` ```java static void returned(Context ctx) { String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault(""); if (customerId.isEmpty()) { signInPage(ctx); return; } String connectionId = ctx.queryParamAsClass("connection_id", String.class).getOrDefault(""); JsonNode connection = Nurishd.call("GET", "/meals/v1/connection/%s/get/document".formatted(connectionId)); if (!connection.path("external_id").asText().equals("shopify-" + customerId)) { throw new ForbiddenResponse(); } if (!connection.path("status").asText().equals("active")) { page(ctx, "

The connection was not approved.

"); return; } connected.put(customerId, connection.path("user").asText()); page(ctx, "

Your Nurish'd account is connected.

"); } ``` A connection whose `external_id` is not this shopper's answers `403`. That stops a shopper from claiming someone else's connection by pasting its id. ## 7. Show meals for the shopper's address `GET /apps/nurishd/meals` answers JSON for your storefront: the meals that can be delivered to the shopper's default Shopify address on the next delivery date. It makes the same chain of calls as [Show meals for an address](/docs/tutorials/show-meals-for-an-address), which explains each one: 1. `GET /meals/v1/zone/query/documents` with the address's city, province code and country code. The first zone found is used. 2. `GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documents` for the next 30 days. The first date is the next delivery date. 3. `GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{date}/get/document` for the products offered on that date. 4. `GET /meals/v1/vendor/{vendor_id}/product/query/documents` for the names and prices, keeping only the products offered. The zone lookup takes the province and the country as two capital letters, such as `ON` and `CA`. Shopify's `countryCodeV2` is the two-letter country code. `provinceCode` is the code of the region, and the lookup needs it to be two letters too. ```python @app.get("/proxy/meals") def meals(): customer_id = request.args.get("logged_in_customer_id", "") if not customer_id: return jsonify(error="not_signed_in"), 401 address = shopify_customer(customer_id)["defaultAddress"] if not address: return jsonify(error="no_default_address"), 400 zones = call( "GET", "/meals/v1/zone/query/documents", { "city": address["city"], "state": address["provinceCode"], "country": address["countryCodeV2"], }, )["data"] if not zones: return jsonify(meals=[]) zone = zones[0] vendor_id = zone["vendor"] zone_id = zone["zone_id"] today = date.today() dates = call( "GET", f"/meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documents", {"from": today.isoformat(), "to": (today + timedelta(days=30)).isoformat()}, )["valid_delivery_dates"] if not dates: return jsonify(meals=[]) day = dates[0][:10] offer = call( "GET", f"/meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{day}/get/document" ) offered = set(offer["all_unique_product_ids"]) found = [ {"product_id": p["product_id"], "name": p["product_name"], "price": p["product_price"]} for p in pages(f"/meals/v1/vendor/{vendor_id}/product/query/documents", {"size": 50}) if p["product_id"] in offered ] return jsonify( vendor=vendor_id, delivery_date=day, currency=zone["zone_currency"], meals=found ) ``` ```javascript app.get('/proxy/meals', async (req, res) => { const customerId = req.query.logged_in_customer_id ?? ''; if (!customerId) return res.status(401).json({ error: 'not_signed_in' }); const address = (await shopifyCustomer(customerId)).defaultAddress; if (!address) return res.status(400).json({ error: 'no_default_address' }); const zones = ( await call('GET', '/meals/v1/zone/query/documents', { params: { city: address.city, state: address.provinceCode, country: address.countryCodeV2, }, }) ).data; if (zones.length === 0) return res.json({ meals: [] }); const zone = zones[0]; const vendorId = zone.vendor; const zoneId = zone.zone_id; const today = new Date(); const later = new Date(today.getTime() + 30 * 24 * 3600 * 1000); const dates = ( await call( 'GET', `/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/query/documents`, { params: { from: today.toISOString().slice(0, 10), to: later.toISOString().slice(0, 10), }, }, ) ).valid_delivery_dates; if (dates.length === 0) return res.json({ meals: [] }); const day = dates[0].slice(0, 10); const offer = await call( 'GET', `/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/${day}/get/document`, ); const offered = new Set(offer.all_unique_product_ids); const found = []; for await (const p of pages( `/meals/v1/vendor/${vendorId}/product/query/documents`, { size: 50 }, )) { if (offered.has(p.product_id)) { found.push({ product_id: p.product_id, name: p.product_name, price: p.product_price, }); } } res.json({ vendor: vendorId, delivery_date: day, currency: zone.zone_currency, meals: found, }); }); ``` ```typescript app.get('/proxy/meals', async (req, res) => { const customerId = String(req.query.logged_in_customer_id ?? ''); if (!customerId) return res.status(401).json({ error: 'not_signed_in' }); const address = (await shopifyCustomer(customerId)).defaultAddress; if (!address) return res.status(400).json({ error: 'no_default_address' }); const zones = ( await call>('GET', '/meals/v1/zone/query/documents', { params: { city: address.city, state: address.provinceCode, country: address.countryCodeV2, }, }) ).data; if (zones.length === 0) return res.json({ meals: [] }); const zone = zones[0]; const vendorId = zone.vendor; const zoneId = zone.zone_id; const today = new Date(); const later = new Date(today.getTime() + 30 * 24 * 3600 * 1000); const dates = ( await call<{ valid_delivery_dates: string[] }>( 'GET', `/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/query/documents`, { params: { from: today.toISOString().slice(0, 10), to: later.toISOString().slice(0, 10), }, }, ) ).valid_delivery_dates; if (dates.length === 0) return res.json({ meals: [] }); const day = dates[0].slice(0, 10); const offer = await call<{ all_unique_product_ids: string[] }>( 'GET', `/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/${day}/get/document`, ); const offered = new Set(offer.all_unique_product_ids); const found = []; for await (const p of pages( `/meals/v1/vendor/${vendorId}/product/query/documents`, { size: 50 }, )) { if (offered.has(p.product_id)) { found.push({ product_id: p.product_id, name: p.product_name, price: p.product_price, }); } } res.json({ vendor: vendorId, delivery_date: day, currency: zone.zone_currency, meals: found, }); }); ``` ```java static void meals(Context ctx) throws Exception { String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault(""); if (customerId.isEmpty()) { ctx.status(401).json(Map.of("error", "not_signed_in")); return; } JsonNode address = shopifyCustomer(customerId).path("defaultAddress"); if (address.isMissingNode() || address.isNull()) { ctx.status(400).json(Map.of("error", "no_default_address")); return; } JsonNode zones = Nurishd.call("GET", "/meals/v1/zone/query/documents", Map.of( "city", address.path("city").asText(), "state", address.path("provinceCode").asText(), "country", address.path("countryCodeV2").asText()), null).path("data"); if (zones.isEmpty()) { ctx.json(Map.of("meals", List.of())); return; } JsonNode zone = zones.get(0); String vendorId = zone.path("vendor").asText(); String zoneId = zone.path("zone_id").asText(); LocalDate today = LocalDate.now(); JsonNode dates = Nurishd.call("GET", "/meals/v1/vendor/%s/zone/%s/delivery-date/query/documents".formatted(vendorId, zoneId), Map.of("from", today.toString(), "to", today.plusDays(30).toString()), null) .path("valid_delivery_dates"); if (dates.isEmpty()) { ctx.json(Map.of("meals", List.of())); return; } String day = dates.get(0).asText().substring(0, 10); JsonNode offer = Nurishd.call("GET", "/meals/v1/vendor/%s/zone/%s/delivery-date/%s/get/document".formatted(vendorId, zoneId, day)); Set offered = new HashSet<>(); offer.path("all_unique_product_ids").forEach(id -> offered.add(id.asText())); List> found = new ArrayList<>(); for (JsonNode p : Nurishd.pages( "/meals/v1/vendor/%s/product/query/documents".formatted(vendorId), Map.of("size", 50))) { if (offered.contains(p.path("product_id").asText())) { found.add(Map.of( "product_id", p.path("product_id").asText(), "name", p.path("product_name").asText(), "price", p.path("product_price").asInt())); } } ctx.json(Map.of( "vendor", vendorId, "delivery_date", day, "currency", zone.path("zone_currency").asText(), "meals", found)); } ``` Your theme calls the route with a relative address. The request goes to your store's domain, Shopify forwards it to your server, and your key never reaches the browser. ```javascript // In your theme's JavaScript. Shopify forwards the request to your server. const res = await fetch('/apps/nurishd/meals'); const answer = await res.json(); for (const meal of answer.meals) { console.log(meal.name, meal.price); } ``` Prices are in cents, in the zone's currency. ## 8. Place an order and take the payment `POST /apps/nurishd/orders` places the order for the connected shopper with `POST /meals/v1/order/create/document`, the same call as in [Place a meal order](/docs/tutorials/place-a-meal-order). The storefront sends the `vendor`, the `delivery_date` and the `line_items` from the meals answer, and a `phone` in international format. The server adds the Nurish'd customer id, and the email and address from Shopify. Shopify forwards the method and the body of a `POST`, so the route reads the JSON body as usual. ```python @app.post("/proxy/orders") def orders(): customer_id = request.args.get("logged_in_customer_id", "") user = connected.get(customer_id) if not user: return jsonify(error="not_connected"), 409 shopper = shopify_customer(customer_id) address = shopper["defaultAddress"] if not address: return jsonify(error="no_default_address"), 400 choice = request.get_json() order = call( "POST", "/meals/v1/order/create/document", body={ "user": user, "order_vendor": choice["vendor"], "order_delivery_date": choice["delivery_date"], "order_shipping_address": { "line1": address["address1"], "line2": address["address2"], "city": address["city"], "state": address["provinceCode"], "postal_code": address["zip"], "country": address["countryCodeV2"], }, "line_items": choice["line_items"], "order_contact_email": shopper["defaultEmailAddress"]["emailAddress"], "order_contact_phone": choice["phone"], }, ) return jsonify( order_id=order["order_id"], stripe_payment_intent=order["stripe_payment_intent"], stripe_publishable_key=order["stripe_publishable_key"], ) ``` ```javascript app.post('/proxy/orders', express.json(), async (req, res) => { const customerId = req.query.logged_in_customer_id ?? ''; const user = connected.get(customerId); if (!user) return res.status(409).json({ error: 'not_connected' }); const shopper = await shopifyCustomer(customerId); const address = shopper.defaultAddress; if (!address) return res.status(400).json({ error: 'no_default_address' }); const choice = req.body; const order = await call('POST', '/meals/v1/order/create/document', { body: { user, order_vendor: choice.vendor, order_delivery_date: choice.delivery_date, order_shipping_address: { line1: address.address1, line2: address.address2, city: address.city, state: address.provinceCode, postal_code: address.zip, country: address.countryCodeV2, }, line_items: choice.line_items, order_contact_email: shopper.defaultEmailAddress.emailAddress, order_contact_phone: choice.phone, }, }); res.json({ order_id: order.order_id, stripe_payment_intent: order.stripe_payment_intent, stripe_publishable_key: order.stripe_publishable_key, }); }); ``` ```typescript app.post('/proxy/orders', express.json(), async (req, res) => { const customerId = String(req.query.logged_in_customer_id ?? ''); const user = connected.get(customerId); if (!user) return res.status(409).json({ error: 'not_connected' }); const shopper = await shopifyCustomer(customerId); const address = shopper.defaultAddress; if (!address) return res.status(400).json({ error: 'no_default_address' }); const choice = req.body as OrderChoice; const order = await call('POST', '/meals/v1/order/create/document', { body: { user, order_vendor: choice.vendor, order_delivery_date: choice.delivery_date, order_shipping_address: { line1: address.address1, line2: address.address2, city: address.city, state: address.provinceCode, postal_code: address.zip, country: address.countryCodeV2, }, line_items: choice.line_items, order_contact_email: shopper.defaultEmailAddress.emailAddress, order_contact_phone: choice.phone, }, }); res.json({ order_id: order.order_id, stripe_payment_intent: order.stripe_payment_intent, stripe_publishable_key: order.stripe_publishable_key, }); }); ``` ```java static void orders(Context ctx) throws Exception { String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault(""); String user = connected.get(customerId); if (user == null) { ctx.status(409).json(Map.of("error", "not_connected")); return; } JsonNode shopper = shopifyCustomer(customerId); JsonNode address = shopper.path("defaultAddress"); if (address.isMissingNode() || address.isNull()) { ctx.status(400).json(Map.of("error", "no_default_address")); return; } JsonNode choice = Nurishd.JSON.readTree(ctx.body()); Map shippingAddress = new HashMap<>(); shippingAddress.put("line1", address.path("address1").asText()); shippingAddress.put("line2", address.path("address2").isNull() ? null : address.path("address2").asText()); shippingAddress.put("city", address.path("city").asText()); shippingAddress.put("state", address.path("provinceCode").asText()); shippingAddress.put("postal_code", address.path("zip").asText()); shippingAddress.put("country", address.path("countryCodeV2").asText()); JsonNode order = Nurishd.call("POST", "/meals/v1/order/create/document", Map.of(), Map.of( "user", user, "order_vendor", choice.path("vendor").asText(), "order_delivery_date", choice.path("delivery_date").asText(), "order_shipping_address", shippingAddress, "line_items", choice.path("line_items"), "order_contact_email", shopper.path("defaultEmailAddress").path("emailAddress").asText(), "order_contact_phone", choice.path("phone").asText())); Map answer = new HashMap<>(); answer.put("order_id", order.path("order_id").asText()); answer.put("stripe_payment_intent", order.path("stripe_payment_intent")); answer.put("stripe_publishable_key", order.path("stripe_publishable_key")); ctx.json(answer); } ``` The route answers the Stripe client secret and publishable key from the order. Your payment page takes them and confirms the payment with Stripe.js, in the browser. Serve that page through the proxy too, for example at `/apps/nurishd/pay`. [Place a meal order](/docs/tutorials/place-a-meal-order) has the page. The order is paid when Nurish'd sends the `order.paid` webhook. Nurish'd sends webhooks straight to your server's own public address, such as `https://your-server.example.com/webhooks/nurishd`, not through the app proxy. [Receive order webhooks](/docs/tutorials/receive-order-webhooks) builds that receiver. ## 9. Run it Start the server. It listens on port 3000. To use another port, set the `PORT` variable. - Python: `python shop.py` - JavaScript: `node shop.js` - TypeScript: `node shop.ts` - Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.Shop` ### Check the signature code without Shopify Shopify's doc has a worked example: the secret `hush` and a query string with its signature. Your code must accept it. Stop the server, start it again with `SHOPIFY_CLIENT_SECRET` set to `hush`, and in a second terminal run: ```bash curl "http://localhost:3000/proxy/connect?extra=1&extra=2&shop=shop-name.myshopify.com&logged_in_customer_id=&path_prefix=%2Fapps%2Fawesome_reviews×tamp=1317327555&signature=e072b6d7e6622d85912a5214b860d3100dc1e73d9bc29f43796ac8c9ff8093cb" ``` The example has no signed-in shopper, so you see the sign-in page: ```text

Sign in to the store first.

Sign in

``` Change one character of the query, for example `extra=2` to `extra=3`, and run it again. Now the server answers `401 Unauthorized`. Set `SHOPIFY_CLIENT_SECRET` back to your client secret and restart the server. ### Try it on your store 1. Start your tunnel to port 3000. The proxy URL you set in step 1 must be the tunnel's public address followed by `/proxy`. 2. Sign in to your store as a test customer who has a default address. 3. Open `https://shop.example.com/apps/nurishd/connect` with your store's domain. You see a page with the link **Continue to Nurish'd**. 4. Select the link and approve. In the Sandbox, the approval page accepts the code `424242`. 5. Nurish'd sends you back to `/apps/nurishd/return`, which says: ```text Your Nurish'd account is connected. ``` 6. Open `https://shop.example.com/apps/nurishd/meals`. You see the meals for your address, for example: ```text {"vendor":"vendor-harbour-kitchen","delivery_date":"2026-04-07","currency":"CAD","meals":[{"product_id":"product-salmon-bowl","name":"Salmon Bowl","price":1495}]} ``` Your vendor, date and meals will differ. ## The whole program Each file is complete. Next to it you need the `nurishd` client from the setup tutorial. ```python # file: shop.py import hashlib import hmac import os import time from datetime import date, timedelta from urllib.parse import parse_qsl import requests from flask import Flask, Response, abort, jsonify, request from nurishd import NurishdError, call, pages SHOPIFY_SHOP = os.environ["SHOPIFY_SHOP"] SHOPIFY_CLIENT_ID = os.environ["SHOPIFY_CLIENT_ID"] SHOPIFY_CLIENT_SECRET = os.environ["SHOPIFY_CLIENT_SECRET"] SHOPIFY_API_VERSION = "2026-10" # For local tests only: send the Shopify calls to a fake server. SHOPIFY_URL = os.environ.get("SHOPIFY_URL", f"https://{SHOPIFY_SHOP}") RETURN_URL = os.environ["RETURN_URL"] app = Flask(__name__) # Shopify customer id -> Nurish'd customer id. A real app keeps this in its database. connected = {} token = {"value": "", "expires_at": 0} def proxy_signature_ok(query_string): """Checks the signature Shopify adds to every app proxy request.""" values = {} signature = "" for name, value in parse_qsl(query_string, keep_blank_values=True): if name == "signature": signature = value else: values.setdefault(name, []).append(value) message = "".join( sorted(f"{name}={','.join(items)}" for name, items in values.items()) ) expected = hmac.new( SHOPIFY_CLIENT_SECRET.encode(), message.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature) @app.before_request def check_signature(): if not proxy_signature_ok(request.query_string.decode()): abort(401) def page(html): """A page Shopify shows inside the store's theme.""" return Response(html, content_type="application/liquid") def sign_in_page(): """Asks the shopper to sign in. Shopify fills in the sign-in link.""" return page( "

Sign in to the store first.

" '

Sign in

' ) def shopify_token(): """Gets an Admin API access token. Shopify's tokens last 24 hours.""" if time.time() < token["expires_at"] - 60: return token["value"] res = requests.post( f"{SHOPIFY_URL}/admin/oauth/access_token", data={ "grant_type": "client_credentials", "client_id": SHOPIFY_CLIENT_ID, "client_secret": SHOPIFY_CLIENT_SECRET, }, timeout=30, ) res.raise_for_status() answer = res.json() token["value"] = answer["access_token"] token["expires_at"] = time.time() + answer["expires_in"] return token["value"] def shopify_customer(customer_id): """Reads a customer's name, email and default address from Shopify.""" query = """ query ($id: ID!) { customer(id: $id) { firstName lastName defaultEmailAddress { emailAddress } defaultAddress { address1 address2 city provinceCode countryCodeV2 zip } } }""" res = requests.post( f"{SHOPIFY_URL}/admin/api/{SHOPIFY_API_VERSION}/graphql.json", headers={"X-Shopify-Access-Token": shopify_token()}, json={ "query": query, "variables": {"id": f"gid://shopify/Customer/{customer_id}"}, }, timeout=30, ) res.raise_for_status() answer = res.json() if answer.get("errors"): raise RuntimeError(f"Shopify said: {answer['errors']}") return answer["data"]["customer"] @app.get("/proxy/connect") def connect(): customer_id = request.args.get("logged_in_customer_id", "") if not customer_id: return sign_in_page() shopper = shopify_customer(customer_id) try: created = call( "POST", "/meals/v1/customer/create/document", body={ "external_id": f"shopify-{customer_id}", "email": shopper["defaultEmailAddress"]["emailAddress"], "first_name": shopper["firstName"], "last_name": shopper["lastName"], "return_url": RETURN_URL, }, ) except NurishdError as error: if error.code == "person_already_connected": return page("

This email is already connected under another store account.

") raise if created["connection"]["status"] == "active": connected[customer_id] = created["user"] return page("

Your Nurish'd account is already connected.

") return page( "

Nurish'd asks you to approve the connection on its own page.

" f'

Continue to Nurish\'d

' ) @app.get("/proxy/return") def returned(): customer_id = request.args.get("logged_in_customer_id", "") if not customer_id: return sign_in_page() connection_id = request.args.get("connection_id", "") connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document") if connection["external_id"] != f"shopify-{customer_id}": abort(403) if connection["status"] != "active": return page("

The connection was not approved.

") connected[customer_id] = connection["user"] return page("

Your Nurish'd account is connected.

") @app.get("/proxy/meals") def meals(): customer_id = request.args.get("logged_in_customer_id", "") if not customer_id: return jsonify(error="not_signed_in"), 401 address = shopify_customer(customer_id)["defaultAddress"] if not address: return jsonify(error="no_default_address"), 400 zones = call( "GET", "/meals/v1/zone/query/documents", { "city": address["city"], "state": address["provinceCode"], "country": address["countryCodeV2"], }, )["data"] if not zones: return jsonify(meals=[]) zone = zones[0] vendor_id = zone["vendor"] zone_id = zone["zone_id"] today = date.today() dates = call( "GET", f"/meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documents", {"from": today.isoformat(), "to": (today + timedelta(days=30)).isoformat()}, )["valid_delivery_dates"] if not dates: return jsonify(meals=[]) day = dates[0][:10] offer = call( "GET", f"/meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{day}/get/document" ) offered = set(offer["all_unique_product_ids"]) found = [ {"product_id": p["product_id"], "name": p["product_name"], "price": p["product_price"]} for p in pages(f"/meals/v1/vendor/{vendor_id}/product/query/documents", {"size": 50}) if p["product_id"] in offered ] return jsonify( vendor=vendor_id, delivery_date=day, currency=zone["zone_currency"], meals=found ) @app.post("/proxy/orders") def orders(): customer_id = request.args.get("logged_in_customer_id", "") user = connected.get(customer_id) if not user: return jsonify(error="not_connected"), 409 shopper = shopify_customer(customer_id) address = shopper["defaultAddress"] if not address: return jsonify(error="no_default_address"), 400 choice = request.get_json() order = call( "POST", "/meals/v1/order/create/document", body={ "user": user, "order_vendor": choice["vendor"], "order_delivery_date": choice["delivery_date"], "order_shipping_address": { "line1": address["address1"], "line2": address["address2"], "city": address["city"], "state": address["provinceCode"], "postal_code": address["zip"], "country": address["countryCodeV2"], }, "line_items": choice["line_items"], "order_contact_email": shopper["defaultEmailAddress"]["emailAddress"], "order_contact_phone": choice["phone"], }, ) return jsonify( order_id=order["order_id"], stripe_payment_intent=order["stripe_payment_intent"], stripe_publishable_key=order["stripe_publishable_key"], ) if __name__ == "__main__": app.run(port=int(os.environ.get("PORT", "3000"))) ``` ```javascript // file: shop.js import crypto from 'node:crypto'; import express from 'express'; import { NurishdError, call, pages } from './nurishd.js'; const SHOPIFY_SHOP = process.env.SHOPIFY_SHOP; const SHOPIFY_CLIENT_ID = process.env.SHOPIFY_CLIENT_ID; const SHOPIFY_CLIENT_SECRET = process.env.SHOPIFY_CLIENT_SECRET; const SHOPIFY_API_VERSION = '2026-10'; // For local tests only: send the Shopify calls to a fake server. const SHOPIFY_URL = process.env.SHOPIFY_URL ?? `https://${SHOPIFY_SHOP}`; const RETURN_URL = process.env.RETURN_URL; const app = express(); // Shopify customer id -> Nurish'd customer id. A real app keeps this in its database. const connected = new Map(); const token = { value: '', expiresAt: 0 }; /** Checks the signature Shopify adds to every app proxy request. */ function proxySignatureOk(queryString) { const values = new Map(); let signature = ''; for (const [name, value] of new URLSearchParams(queryString)) { if (name === 'signature') signature = value; else values.set(name, [...(values.get(name) ?? []), value]); } const message = [...values] .map(([name, items]) => `${name}=${items.join(',')}`) .sort() .join(''); const expected = crypto .createHmac('sha256', SHOPIFY_CLIENT_SECRET) .update(message) .digest('hex'); return ( signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)) ); } app.use((req, res, next) => { const queryString = req.originalUrl.split('?')[1] ?? ''; if (!proxySignatureOk(queryString)) return res.sendStatus(401); next(); }); /** A page Shopify shows inside the store's theme. */ function page(res, html) { res.type('application/liquid').end(html); } /** Asks the shopper to sign in. Shopify fills in the sign-in link. */ function signInPage(res) { page( res, '

Sign in to the store first.

Sign in

', ); } /** Gets an Admin API access token. Shopify's tokens last 24 hours. */ async function shopifyToken() { if (Date.now() < token.expiresAt - 60_000) return token.value; const res = await fetch(`${SHOPIFY_URL}/admin/oauth/access_token`, { method: 'POST', body: new URLSearchParams({ grant_type: 'client_credentials', client_id: SHOPIFY_CLIENT_ID, client_secret: SHOPIFY_CLIENT_SECRET, }), }); if (!res.ok) throw new Error(`Shopify token: ${res.status}`); const answer = await res.json(); token.value = answer.access_token; token.expiresAt = Date.now() + answer.expires_in * 1000; return token.value; } /** Reads a customer's name, email and default address from Shopify. */ async function shopifyCustomer(customerId) { const query = ` query ($id: ID!) { customer(id: $id) { firstName lastName defaultEmailAddress { emailAddress } defaultAddress { address1 address2 city provinceCode countryCodeV2 zip } } }`; const res = await fetch( `${SHOPIFY_URL}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Shopify-Access-Token': await shopifyToken(), }, body: JSON.stringify({ query, variables: { id: `gid://shopify/Customer/${customerId}` }, }), }, ); if (!res.ok) throw new Error(`Shopify customer: ${res.status}`); const answer = await res.json(); if (answer.errors) throw new Error(`Shopify said: ${JSON.stringify(answer.errors)}`); return answer.data.customer; } app.get('/proxy/connect', async (req, res) => { const customerId = req.query.logged_in_customer_id ?? ''; if (!customerId) return signInPage(res); const shopper = await shopifyCustomer(customerId); let created; try { created = await call('POST', '/meals/v1/customer/create/document', { body: { external_id: `shopify-${customerId}`, email: shopper.defaultEmailAddress.emailAddress, first_name: shopper.firstName, last_name: shopper.lastName, return_url: RETURN_URL, }, }); } catch (error) { if ( error instanceof NurishdError && error.code === 'person_already_connected' ) { return page( res, '

This email is already connected under another store account.

', ); } throw error; } if (created.connection.status === 'active') { connected.set(customerId, created.user); return page(res, "

Your Nurish'd account is already connected.

"); } page( res, "

Nurish'd asks you to approve the connection on its own page.

" + `

Continue to Nurish'd

`, ); }); app.get('/proxy/return', async (req, res) => { const customerId = req.query.logged_in_customer_id ?? ''; if (!customerId) return signInPage(res); const connectionId = req.query.connection_id ?? ''; const connection = await call( 'GET', `/meals/v1/connection/${connectionId}/get/document`, ); if (connection.external_id !== `shopify-${customerId}`) return res.sendStatus(403); if (connection.status !== 'active') return page(res, '

The connection was not approved.

'); connected.set(customerId, connection.user); page(res, "

Your Nurish'd account is connected.

"); }); app.get('/proxy/meals', async (req, res) => { const customerId = req.query.logged_in_customer_id ?? ''; if (!customerId) return res.status(401).json({ error: 'not_signed_in' }); const address = (await shopifyCustomer(customerId)).defaultAddress; if (!address) return res.status(400).json({ error: 'no_default_address' }); const zones = ( await call('GET', '/meals/v1/zone/query/documents', { params: { city: address.city, state: address.provinceCode, country: address.countryCodeV2, }, }) ).data; if (zones.length === 0) return res.json({ meals: [] }); const zone = zones[0]; const vendorId = zone.vendor; const zoneId = zone.zone_id; const today = new Date(); const later = new Date(today.getTime() + 30 * 24 * 3600 * 1000); const dates = ( await call( 'GET', `/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/query/documents`, { params: { from: today.toISOString().slice(0, 10), to: later.toISOString().slice(0, 10), }, }, ) ).valid_delivery_dates; if (dates.length === 0) return res.json({ meals: [] }); const day = dates[0].slice(0, 10); const offer = await call( 'GET', `/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/${day}/get/document`, ); const offered = new Set(offer.all_unique_product_ids); const found = []; for await (const p of pages( `/meals/v1/vendor/${vendorId}/product/query/documents`, { size: 50 }, )) { if (offered.has(p.product_id)) { found.push({ product_id: p.product_id, name: p.product_name, price: p.product_price, }); } } res.json({ vendor: vendorId, delivery_date: day, currency: zone.zone_currency, meals: found, }); }); app.post('/proxy/orders', express.json(), async (req, res) => { const customerId = req.query.logged_in_customer_id ?? ''; const user = connected.get(customerId); if (!user) return res.status(409).json({ error: 'not_connected' }); const shopper = await shopifyCustomer(customerId); const address = shopper.defaultAddress; if (!address) return res.status(400).json({ error: 'no_default_address' }); const choice = req.body; const order = await call('POST', '/meals/v1/order/create/document', { body: { user, order_vendor: choice.vendor, order_delivery_date: choice.delivery_date, order_shipping_address: { line1: address.address1, line2: address.address2, city: address.city, state: address.provinceCode, postal_code: address.zip, country: address.countryCodeV2, }, line_items: choice.line_items, order_contact_email: shopper.defaultEmailAddress.emailAddress, order_contact_phone: choice.phone, }, }); res.json({ order_id: order.order_id, stripe_payment_intent: order.stripe_payment_intent, stripe_publishable_key: order.stripe_publishable_key, }); }); app.listen(Number(process.env.PORT ?? 3000), () => { console.log(`Listening on port ${process.env.PORT ?? 3000}`); }); ``` ```typescript // file: shop.ts import crypto from 'node:crypto'; import express, { type Response } from 'express'; import { NurishdError, call, pages, type Page } from './nurishd.ts'; const SHOPIFY_SHOP = process.env.SHOPIFY_SHOP ?? ''; const SHOPIFY_CLIENT_ID = process.env.SHOPIFY_CLIENT_ID ?? ''; const SHOPIFY_CLIENT_SECRET = process.env.SHOPIFY_CLIENT_SECRET ?? ''; const SHOPIFY_API_VERSION = '2026-10'; // For local tests only: send the Shopify calls to a fake server. const SHOPIFY_URL = process.env.SHOPIFY_URL ?? `https://${SHOPIFY_SHOP}`; const RETURN_URL = process.env.RETURN_URL ?? ''; /** A Shopify address, with the fields the query asks for. */ interface ShopifyAddress { address1: string; address2: string | null; city: string; provinceCode: string; countryCodeV2: string; zip: string; } /** A Shopify customer, with the fields the query asks for. */ interface ShopifyCustomer { firstName: string; lastName: string; defaultEmailAddress: { emailAddress: string }; defaultAddress: ShopifyAddress | null; } /** The parts of Nurish'd answers this server reads. */ interface Connection { user: string; external_id: string; status: string; } interface CreatedCustomer { user: string; connection: Connection; connect_url: string; } interface Zone { zone_id: string; vendor: string; zone_currency: string; } interface Product { product_id: string; product_name: string; product_price: number; } interface Order { order_id: string; stripe_payment_intent: object | null; stripe_publishable_key: string | null; } /** What the storefront sends to place an order. */ interface OrderChoice { vendor: string; delivery_date: string; line_items: { line_item_product_id: string; line_quantity: number }[]; phone: string; } const app = express(); // Shopify customer id -> Nurish'd customer id. A real app keeps this in its database. const connected = new Map(); const token = { value: '', expiresAt: 0 }; /** Checks the signature Shopify adds to every app proxy request. */ function proxySignatureOk(queryString: string): boolean { const values = new Map(); let signature = ''; for (const [name, value] of new URLSearchParams(queryString)) { if (name === 'signature') signature = value; else values.set(name, [...(values.get(name) ?? []), value]); } const message = [...values] .map(([name, items]) => `${name}=${items.join(',')}`) .sort() .join(''); const expected = crypto .createHmac('sha256', SHOPIFY_CLIENT_SECRET) .update(message) .digest('hex'); return ( signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)) ); } app.use((req, res, next) => { const queryString = req.originalUrl.split('?')[1] ?? ''; if (!proxySignatureOk(queryString)) return res.sendStatus(401); next(); }); /** A page Shopify shows inside the store's theme. */ function page(res: Response, html: string) { res.type('application/liquid').end(html); } /** Asks the shopper to sign in. Shopify fills in the sign-in link. */ function signInPage(res: Response) { page( res, '

Sign in to the store first.

Sign in

', ); } /** Gets an Admin API access token. Shopify's tokens last 24 hours. */ async function shopifyToken(): Promise { if (Date.now() < token.expiresAt - 60_000) return token.value; const res = await fetch(`${SHOPIFY_URL}/admin/oauth/access_token`, { method: 'POST', body: new URLSearchParams({ grant_type: 'client_credentials', client_id: SHOPIFY_CLIENT_ID, client_secret: SHOPIFY_CLIENT_SECRET, }), }); if (!res.ok) throw new Error(`Shopify token: ${res.status}`); const answer = (await res.json()) as { access_token: string; expires_in: number; }; token.value = answer.access_token; token.expiresAt = Date.now() + answer.expires_in * 1000; return token.value; } /** Reads a customer's name, email and default address from Shopify. */ async function shopifyCustomer(customerId: string): Promise { const query = ` query ($id: ID!) { customer(id: $id) { firstName lastName defaultEmailAddress { emailAddress } defaultAddress { address1 address2 city provinceCode countryCodeV2 zip } } }`; const res = await fetch( `${SHOPIFY_URL}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Shopify-Access-Token': await shopifyToken(), }, body: JSON.stringify({ query, variables: { id: `gid://shopify/Customer/${customerId}` }, }), }, ); if (!res.ok) throw new Error(`Shopify customer: ${res.status}`); const answer = (await res.json()) as { data: { customer: ShopifyCustomer }; errors?: unknown; }; if (answer.errors) throw new Error(`Shopify said: ${JSON.stringify(answer.errors)}`); return answer.data.customer; } app.get('/proxy/connect', async (req, res) => { const customerId = String(req.query.logged_in_customer_id ?? ''); if (!customerId) return signInPage(res); const shopper = await shopifyCustomer(customerId); let created: CreatedCustomer; try { created = await call( 'POST', '/meals/v1/customer/create/document', { body: { external_id: `shopify-${customerId}`, email: shopper.defaultEmailAddress.emailAddress, first_name: shopper.firstName, last_name: shopper.lastName, return_url: RETURN_URL, }, }, ); } catch (error) { if ( error instanceof NurishdError && error.code === 'person_already_connected' ) { return page( res, '

This email is already connected under another store account.

', ); } throw error; } if (created.connection.status === 'active') { connected.set(customerId, created.user); return page(res, "

Your Nurish'd account is already connected.

"); } page( res, "

Nurish'd asks you to approve the connection on its own page.

" + `

Continue to Nurish'd

`, ); }); app.get('/proxy/return', async (req, res) => { const customerId = String(req.query.logged_in_customer_id ?? ''); if (!customerId) return signInPage(res); const connectionId = String(req.query.connection_id ?? ''); const connection = await call( 'GET', `/meals/v1/connection/${connectionId}/get/document`, ); if (connection.external_id !== `shopify-${customerId}`) return res.sendStatus(403); if (connection.status !== 'active') return page(res, '

The connection was not approved.

'); connected.set(customerId, connection.user); page(res, "

Your Nurish'd account is connected.

"); }); app.get('/proxy/meals', async (req, res) => { const customerId = String(req.query.logged_in_customer_id ?? ''); if (!customerId) return res.status(401).json({ error: 'not_signed_in' }); const address = (await shopifyCustomer(customerId)).defaultAddress; if (!address) return res.status(400).json({ error: 'no_default_address' }); const zones = ( await call>('GET', '/meals/v1/zone/query/documents', { params: { city: address.city, state: address.provinceCode, country: address.countryCodeV2, }, }) ).data; if (zones.length === 0) return res.json({ meals: [] }); const zone = zones[0]; const vendorId = zone.vendor; const zoneId = zone.zone_id; const today = new Date(); const later = new Date(today.getTime() + 30 * 24 * 3600 * 1000); const dates = ( await call<{ valid_delivery_dates: string[] }>( 'GET', `/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/query/documents`, { params: { from: today.toISOString().slice(0, 10), to: later.toISOString().slice(0, 10), }, }, ) ).valid_delivery_dates; if (dates.length === 0) return res.json({ meals: [] }); const day = dates[0].slice(0, 10); const offer = await call<{ all_unique_product_ids: string[] }>( 'GET', `/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/${day}/get/document`, ); const offered = new Set(offer.all_unique_product_ids); const found = []; for await (const p of pages( `/meals/v1/vendor/${vendorId}/product/query/documents`, { size: 50 }, )) { if (offered.has(p.product_id)) { found.push({ product_id: p.product_id, name: p.product_name, price: p.product_price, }); } } res.json({ vendor: vendorId, delivery_date: day, currency: zone.zone_currency, meals: found, }); }); app.post('/proxy/orders', express.json(), async (req, res) => { const customerId = String(req.query.logged_in_customer_id ?? ''); const user = connected.get(customerId); if (!user) return res.status(409).json({ error: 'not_connected' }); const shopper = await shopifyCustomer(customerId); const address = shopper.defaultAddress; if (!address) return res.status(400).json({ error: 'no_default_address' }); const choice = req.body as OrderChoice; const order = await call('POST', '/meals/v1/order/create/document', { body: { user, order_vendor: choice.vendor, order_delivery_date: choice.delivery_date, order_shipping_address: { line1: address.address1, line2: address.address2, city: address.city, state: address.provinceCode, postal_code: address.zip, country: address.countryCodeV2, }, line_items: choice.line_items, order_contact_email: shopper.defaultEmailAddress.emailAddress, order_contact_phone: choice.phone, }, }); res.json({ order_id: order.order_id, stripe_payment_intent: order.stripe_payment_intent, stripe_publishable_key: order.stripe_publishable_key, }); }); app.listen(Number(process.env.PORT ?? 3000), () => { console.log(`Listening on port ${process.env.PORT ?? 3000}`); }); ``` ```java // file: src/main/java/tutorial/Shop.java package tutorial; import com.fasterxml.jackson.databind.JsonNode; import io.javalin.Javalin; import io.javalin.http.Context; import io.javalin.http.ForbiddenResponse; import io.javalin.http.UnauthorizedResponse; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.HexFormat; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class Shop { static final String SHOPIFY_SHOP = System.getenv("SHOPIFY_SHOP"); static final String SHOPIFY_CLIENT_ID = System.getenv("SHOPIFY_CLIENT_ID"); static final String SHOPIFY_CLIENT_SECRET = System.getenv("SHOPIFY_CLIENT_SECRET"); static final String SHOPIFY_API_VERSION = "2026-10"; // For local tests only: send the Shopify calls to a fake server. static final String SHOPIFY_URL = System.getenv().getOrDefault("SHOPIFY_URL", "https://" + SHOPIFY_SHOP); static final String RETURN_URL = System.getenv("RETURN_URL"); static final HttpClient HTTP = HttpClient.newHttpClient(); // Shopify customer id -> Nurish'd customer id. A real app keeps this in its database. static final Map connected = new HashMap<>(); static String token = ""; static long tokenExpiresAt = 0; /** Checks the signature Shopify adds to every app proxy request. */ static boolean proxySignatureOk(String queryString) throws Exception { Map> values = new HashMap<>(); String signature = ""; for (String pair : (queryString == null ? "" : queryString).split("&")) { if (pair.isEmpty()) continue; String[] parts = pair.split("=", 2); String name = URLDecoder.decode(parts[0], StandardCharsets.UTF_8); String value = parts.length > 1 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : ""; if (name.equals("signature")) signature = value; else values.computeIfAbsent(name, key -> new ArrayList<>()).add(value); } List pieces = new ArrayList<>(); values.forEach((name, items) -> pieces.add(name + "=" + String.join(",", items))); pieces.sort(null); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(SHOPIFY_CLIENT_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); String expected = HexFormat.of() .formatHex(mac.doFinal(String.join("", pieces).getBytes(StandardCharsets.UTF_8))); return MessageDigest.isEqual( expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8)); } /** A page Shopify shows inside the store's theme. */ static void page(Context ctx, String html) { ctx.contentType("application/liquid").result(html); } /** Asks the shopper to sign in. Shopify fills in the sign-in link. */ static void signInPage(Context ctx) { page(ctx, "

Sign in to the store first.

" + "

Sign in

"); } /** Gets an Admin API access token. Shopify's tokens last 24 hours. */ static synchronized String shopifyToken() throws Exception { if (System.currentTimeMillis() < tokenExpiresAt - 60_000) return token; String form = "grant_type=client_credentials" + "&client_id=" + URLEncoder.encode(SHOPIFY_CLIENT_ID, StandardCharsets.UTF_8) + "&client_secret=" + URLEncoder.encode(SHOPIFY_CLIENT_SECRET, StandardCharsets.UTF_8); HttpRequest request = HttpRequest.newBuilder(URI.create(SHOPIFY_URL + "/admin/oauth/access_token")) .header("Content-Type", "application/x-www-form-urlencoded") .POST(HttpRequest.BodyPublishers.ofString(form)) .build(); HttpResponse res = HTTP.send(request, HttpResponse.BodyHandlers.ofString()); if (res.statusCode() != 200) throw new IllegalStateException("Shopify token: " + res.statusCode()); JsonNode answer = Nurishd.JSON.readTree(res.body()); token = answer.path("access_token").asText(); tokenExpiresAt = System.currentTimeMillis() + answer.path("expires_in").asLong() * 1000; return token; } /** Reads a customer's name, email and default address from Shopify. */ static JsonNode shopifyCustomer(String customerId) throws Exception { String query = """ query ($id: ID!) { customer(id: $id) { firstName lastName defaultEmailAddress { emailAddress } defaultAddress { address1 address2 city provinceCode countryCodeV2 zip } } }"""; String body = Nurishd.JSON.writeValueAsString(Map.of( "query", query, "variables", Map.of("id", "gid://shopify/Customer/" + customerId))); HttpRequest request = HttpRequest.newBuilder( URI.create(SHOPIFY_URL + "/admin/api/" + SHOPIFY_API_VERSION + "/graphql.json")) .header("Content-Type", "application/json") .header("X-Shopify-Access-Token", shopifyToken()) .POST(HttpRequest.BodyPublishers.ofString(body)) .build(); HttpResponse res = HTTP.send(request, HttpResponse.BodyHandlers.ofString()); if (res.statusCode() != 200) throw new IllegalStateException("Shopify customer: " + res.statusCode()); JsonNode answer = Nurishd.JSON.readTree(res.body()); if (answer.has("errors")) throw new IllegalStateException("Shopify said: " + answer.get("errors")); return answer.path("data").path("customer"); } static void connect(Context ctx) throws Exception { String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault(""); if (customerId.isEmpty()) { signInPage(ctx); return; } JsonNode shopper = shopifyCustomer(customerId); JsonNode created; try { created = Nurishd.call("POST", "/meals/v1/customer/create/document", Map.of(), Map.of( "external_id", "shopify-" + customerId, "email", shopper.path("defaultEmailAddress").path("emailAddress").asText(), "first_name", shopper.path("firstName").asText(), "last_name", shopper.path("lastName").asText(), "return_url", RETURN_URL)); } catch (Nurishd.NurishdException error) { if (!error.code.equals("person_already_connected")) throw error; page(ctx, "

This email is already connected under another store account.

"); return; } if (created.path("connection").path("status").asText().equals("active")) { connected.put(customerId, created.path("user").asText()); page(ctx, "

Your Nurish'd account is already connected.

"); return; } page(ctx, "

Nurish'd asks you to approve the connection on its own page.

" + "

Continue to Nurish'd

"); } static void returned(Context ctx) { String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault(""); if (customerId.isEmpty()) { signInPage(ctx); return; } String connectionId = ctx.queryParamAsClass("connection_id", String.class).getOrDefault(""); JsonNode connection = Nurishd.call("GET", "/meals/v1/connection/%s/get/document".formatted(connectionId)); if (!connection.path("external_id").asText().equals("shopify-" + customerId)) { throw new ForbiddenResponse(); } if (!connection.path("status").asText().equals("active")) { page(ctx, "

The connection was not approved.

"); return; } connected.put(customerId, connection.path("user").asText()); page(ctx, "

Your Nurish'd account is connected.

"); } static void meals(Context ctx) throws Exception { String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault(""); if (customerId.isEmpty()) { ctx.status(401).json(Map.of("error", "not_signed_in")); return; } JsonNode address = shopifyCustomer(customerId).path("defaultAddress"); if (address.isMissingNode() || address.isNull()) { ctx.status(400).json(Map.of("error", "no_default_address")); return; } JsonNode zones = Nurishd.call("GET", "/meals/v1/zone/query/documents", Map.of( "city", address.path("city").asText(), "state", address.path("provinceCode").asText(), "country", address.path("countryCodeV2").asText()), null).path("data"); if (zones.isEmpty()) { ctx.json(Map.of("meals", List.of())); return; } JsonNode zone = zones.get(0); String vendorId = zone.path("vendor").asText(); String zoneId = zone.path("zone_id").asText(); LocalDate today = LocalDate.now(); JsonNode dates = Nurishd.call("GET", "/meals/v1/vendor/%s/zone/%s/delivery-date/query/documents".formatted(vendorId, zoneId), Map.of("from", today.toString(), "to", today.plusDays(30).toString()), null) .path("valid_delivery_dates"); if (dates.isEmpty()) { ctx.json(Map.of("meals", List.of())); return; } String day = dates.get(0).asText().substring(0, 10); JsonNode offer = Nurishd.call("GET", "/meals/v1/vendor/%s/zone/%s/delivery-date/%s/get/document".formatted(vendorId, zoneId, day)); Set offered = new HashSet<>(); offer.path("all_unique_product_ids").forEach(id -> offered.add(id.asText())); List> found = new ArrayList<>(); for (JsonNode p : Nurishd.pages( "/meals/v1/vendor/%s/product/query/documents".formatted(vendorId), Map.of("size", 50))) { if (offered.contains(p.path("product_id").asText())) { found.add(Map.of( "product_id", p.path("product_id").asText(), "name", p.path("product_name").asText(), "price", p.path("product_price").asInt())); } } ctx.json(Map.of( "vendor", vendorId, "delivery_date", day, "currency", zone.path("zone_currency").asText(), "meals", found)); } static void orders(Context ctx) throws Exception { String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault(""); String user = connected.get(customerId); if (user == null) { ctx.status(409).json(Map.of("error", "not_connected")); return; } JsonNode shopper = shopifyCustomer(customerId); JsonNode address = shopper.path("defaultAddress"); if (address.isMissingNode() || address.isNull()) { ctx.status(400).json(Map.of("error", "no_default_address")); return; } JsonNode choice = Nurishd.JSON.readTree(ctx.body()); Map shippingAddress = new HashMap<>(); shippingAddress.put("line1", address.path("address1").asText()); shippingAddress.put("line2", address.path("address2").isNull() ? null : address.path("address2").asText()); shippingAddress.put("city", address.path("city").asText()); shippingAddress.put("state", address.path("provinceCode").asText()); shippingAddress.put("postal_code", address.path("zip").asText()); shippingAddress.put("country", address.path("countryCodeV2").asText()); JsonNode order = Nurishd.call("POST", "/meals/v1/order/create/document", Map.of(), Map.of( "user", user, "order_vendor", choice.path("vendor").asText(), "order_delivery_date", choice.path("delivery_date").asText(), "order_shipping_address", shippingAddress, "line_items", choice.path("line_items"), "order_contact_email", shopper.path("defaultEmailAddress").path("emailAddress").asText(), "order_contact_phone", choice.path("phone").asText())); Map answer = new HashMap<>(); answer.put("order_id", order.path("order_id").asText()); answer.put("stripe_payment_intent", order.path("stripe_payment_intent")); answer.put("stripe_publishable_key", order.path("stripe_publishable_key")); ctx.json(answer); } public static void main(String[] args) { int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "3000")); Javalin app = Javalin.create(); app.before(ctx -> { if (!proxySignatureOk(ctx.queryString())) throw new UnauthorizedResponse(); }); app.get("/proxy/connect", Shop::connect); app.get("/proxy/return", Shop::returned); app.get("/proxy/meals", Shop::meals); app.post("/proxy/orders", Shop::orders); app.start(port); } } ``` ## Optional: keep a record in Shopify You can save the Nurish'd customer id on the Shopify customer, so store staff see it in the Shopify admin. Shopify calls such an extra field a metafield. The [metafieldsSet](https://shopify.dev/docs/api/admin-graphql/latest/mutations/metafieldsSet) mutation writes it. A mutation is a GraphQL request that changes data. It needs the scope `write_customers`, because it changes a customer. Add that scope to a new version of your app, as in step 1, and approve it in your store. Send this the same way `shopify_customer` sends its query, with the ids of your shopper: ```graphql mutation { metafieldsSet( metafields: [ { ownerId: "gid://shopify/Customer/1001" namespace: "nurishd" key: "customer_id" type: "single_line_text_field" value: "6f1c0d2e-0000-4000-8000-000000000101" } ] ) { userErrors { field message } } } ``` An empty `userErrors` list means it was saved. ## If something goes wrong A Nurish'd or Shopify error inside a route makes your server answer `500`. The server's log then shows the error. | What you see | Why | What to do | | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Every request to your server answers `401`. | The signature does not verify. The secret is wrong, your code parsed the query and built it again, or something in front of your server changed the query string. | Use the Client secret of this app. Check the signature on the raw query string, as in step 2. Make sure nothing in front of your server rewrites the query. Test with Shopify's example in step 9. | | `401` when you open your server's address yourself. | Only Shopify adds the signature. | Open the store address, `/apps/nurishd/...`, not your server's. | | The sign-in page, although you are signed in. | `logged_in_customer_id` is empty. The shopper is not signed in to this store. | Sign in on the store's own domain, then open the page again. | | `500`, and the log shows `422 validation_error` from `POST /meals/v1/customer/create/document`. | The return URL is not registered in the Nurish'd console, or it differs from `RETURN_URL`. | Add the exact URL under **Settings**, **Return URLs**. See [Company settings](/docs/console/company-settings). | | The page says the email is already connected under another store account. | Create answered `409 person_already_connected`: the email is connected to your company under another `external_id`. | Keep using the first `external_id` for that person. See [Connections](/docs/concepts/connections#one-external-id-per-person). | | `{"error":"no_default_address"}` | The shopper has no default address in Shopify. | Ask the shopper to add an address to their store account. | | `{"meals":[]}` | No zone was found for the address, or no delivery date is open in the next 30 days. The zone lookup compares city, province and country letter for letter, and case counts. | Check the spelling of the city in the shopper's address. See [Catalog](/docs/meals/catalog). | | `500`, and the log shows `Shopify said:` with `not approved to use` a field. | Your app may not read that protected customer field. | Select the fields in the Dev Dashboard, as in step 1. | | `500`, and the log shows `Shopify token:` with an error status. | Shopify refused the client credentials. The grant works only with this app's Client ID and Client secret, for a store in the same organization as the app. | See [Authenticate an app for stores in your organization](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant). | | `403` from `/apps/nurishd/return`. | The connection's `external_id` is not this shopper's. | Start again from `/apps/nurishd/connect` while signed in as that shopper. | ## Next - [Place a meal order](/docs/tutorials/place-a-meal-order): the payment page with Stripe.js. - [Receive order webhooks](/docs/tutorials/receive-order-webhooks): learn when the order is paid. - [Show meals for an address](/docs/tutorials/show-meals-for-an-address): zones, delivery dates and the offer of a date. - [Connections](/docs/concepts/connections): statuses, scopes and return URLs. --- # Authentication Send your API key in the X-Partner-API-Key header, store it safely, and roll or revoke it without downtime. You will authenticate every call with an API key, store it safely, roll it without downtime, and check what it can do. ## The header Send the key in `X-Partner-API-Key` on every call to `https://api.dev.nurishd.ca`. ```bash curl https://api.dev.nurishd.ca/developer/v1/key/get/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/developer/v1/key/get/document', { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/developer/v1/key/get/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) ``` There is no other way to authenticate. Do not send the key in a query string. ## Key anatomy A key is a prefix followed by 64 hex characters. ```text nk-test-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef nk-prod-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef ``` | Prefix | Environment | | ---------- | ----------- | | `nk-test-` | Sandbox | | `nk-prod-` | Production | The prefix decides where the call goes. Both reach `https://api.dev.nurishd.ca`. - The console shows the full key once, when you create it. Nurish'd does not keep it in a form it can show you again. If you lose it, create a new key. - A key that fails for any reason (missing, malformed, unknown, revoked or expired) answers `401 invalid_api_key`. The answers are identical on purpose. - A key with no narrowed scopes follows the company's scopes. A key can never hold a scope the company lacks. See [Scopes](/docs/concepts/scopes). - No key can be created until the company owner accepts the API terms. Production keys need a company that Nurish'd marked Live. ## Store keys safely - Read keys from environment variables or a secret manager. Never commit them. - Never ship a key in a browser, a mobile app or a public repository. Call the API from your server. - Use one key per service so you can revoke one without stopping the others. - Narrow a key to the scopes its job needs. A reporting job should not hold write scopes. - Never put a key in a log line, a support email or an AI prompt. If a key leaks, revoke it in the console at once. A revoked key answers `401 invalid_api_key`. ## Check a key `GET /developer/v1/key/get/document` returns the key you call it with: its `name`, `mode`, the `scopes` it holds now, your company (`company_id`, `company_name` and `company_status`) and the calls per minute it may make (`rate_limit_per_minute`). It needs no scope. ```json { "key_id": "key-0001", "name": "Order service", "mode": "test", "scopes": ["catalog:read", "order:read", "order:write"], "company_id": "company-0001", "company_name": "Example Foods", "company_status": "Sandbox", "rate_limit_per_minute": 25 } ``` Use it in a deploy check to confirm the key works and has the access you expect. ## Roll a key without downtime Rolling makes a new key and sets the old one to expire after a window you choose: now, 1 hour, 1 day or 7 days. 1. Roll the key in the console and pick a window long enough to deploy, such as 1 day. 2. Copy the new key. It is shown once. 3. Deploy the new key to every service. 4. Check each service with `GET /developer/v1/key/get/document`. 5. The old key stops working when its window ends. Choose "now" only if the old key leaked. See [Managing keys](/docs/console/managing-keys) for who can roll keys in each environment. ## Revoke a key Revoke a key in the console when a service is retired or a key may have leaked. A revoked key cannot be restored. Create a new key instead. Removing a member does not revoke the keys they made, because keys belong to the company. ## Next - [Scopes](/docs/concepts/scopes): what a key may do. - [Managing keys](/docs/console/managing-keys): create, roll and revoke in the console. - [Errors](/docs/concepts/errors): `invalid_api_key`, `scope_not_granted` and the rest. --- # Scopes The ten API scopes, which ones need a BAA, and how a key's scopes narrow the company's scopes. You will know which scope each route needs, how a key's scopes relate to the company's, and why patient data needs a BAA even to read. ## The ten scopes Nurish'd grants scopes to your company. Each scope has the form `resource:action`. | Scope | Lets a key | Needs a BAA | | ---------------------- | ------------------------------------------------------------------------------------------------------- | ----------- | | `catalog:read` | Read vendors, menus, products, delivery zones and delivery dates | No | | `order:write` | Create a customer, revoke their connection, place orders, and save a customer's card | No | | `order:read` | Read a customer, a connection, the orders it placed, and a customer's saved cards | No | | `specialist:read` | List specialists, their services and open times | No | | `patient:write` | Create a patient, read a patient, read or revoke a care connection, and save and list a patient's cards | Yes | | `booking:read` | List and read the bookings it made | Yes | | `booking:write` | Book and cancel visits | Yes | | `report:read` | Read signed reports of its bookings and see `report.signed` events | Yes | | `health-profile:read` | Read a connected patient's health profile | Yes | | `health-profile:write` | Update a connected patient's health profile | Yes | Every scope has routes. See [Care](/docs/care/connecting-a-patient), [Visit reports](/docs/care/reports) and [Health profiles](/docs/care/health-profiles). ## Company scopes and key scopes - **The company holds scopes.** Only Nurish'd grants and removes them. - **A key follows the company by default.** A key with no narrowed scopes holds all of the company's scopes. - **A key can be narrowed.** An owner or admin can pick fewer scopes for one key, for example only `catalog:read`. - **A key can never hold a scope the company lacks.** If Nurish'd removes a scope from the company, every key loses it within a minute. Check what a key holds now with `GET /developer/v1/key/get/document`. Its `scopes` field is the key's scopes that your company still holds. A call without the needed scope answers `403 scope_not_granted`: ```json { "error": { "code": "scope_not_granted", "message": "This key does not hold the scope this route needs.", "request_id": "req-0001" } } ``` The fix is to narrow less (use a key with the scope) or to ask Nurish'd to grant the scope to the company. Retrying does not help. Events follow scopes too. A key lists and receives only the event types its scopes allow. See [Events](/docs/events/events). ## The BAA rule A BAA is a business associate agreement. Nurish'd records its signing date on your company. - Nurish'd cannot grant a scope marked "Yes" above to a company with no BAA. - If the BAA is cleared, those scopes disappear from the company and from every key within a minute. - A company with no BAA can use `catalog:read`, `order:read`, `order:write` and `specialist:read`, and nothing about any patient. ### Why read needs a BAA too A booking says that a person sees a dietitian at a given time. Reading it discloses health information exactly as writing it does. So `booking:read` and `report:read` need a BAA, not only the write scopes. See [BAA handling](/docs/care/baa) for what a company without a BAA can do. The card routes follow the same scopes. Under care, starting, confirming and listing a card all need `patient:write`. Under meals, starting and confirming need `order:write` and listing needs `order:read`. See [Saving a card](/docs/care/saving-a-card) and [Saving a card for a customer](/docs/meals/saving-a-card). ## Connection scopes are different Company scopes say what your company may ask for. A connection scope says what one customer or patient approved. They have different names, such as `meals.orders`. See [Connections](/docs/concepts/connections). ## Next - [Connections](/docs/concepts/connections): what a customer approves. - [BAA handling](/docs/care/baa): the rules for care scopes. - [Managing keys](/docs/console/managing-keys): narrow a key in the console. --- # Errors The error shape, every error code with its status and what to do, request ids and which errors are safe to retry. You will read any error from the API, find its code in a table, and know whether to retry. ## The shape Every route answers errors in the same shape, a `422` included. ```json { "error": { "code": "invalid_api_key", "message": "The API key is not valid.", "request_id": "req-0001" } } ``` - Branch on `code`, never on `message`. Messages can change. - `request_id` equals the `X-Request-Id` response header. Log it and send it to [support](/docs/resources/support). - Ignore codes you do not know. A new code can ship for a new failure without a new version. ## Codes | Code | Status | Meaning and what to do | | --------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------ | | `bad_request` | 400 | The request is malformed or breaks a rule, such as a date range over 60 days. Fix the request. | | `bad_request` | 409 | Two rolls of a webhook signing secret happened at the same moment. Try again. | | `validation_error` | 422 | A field is missing or invalid. Fix the field. Do not retry unchanged. | | `delivery_not_available` | 422 | The vendor does not deliver to the address, or not on that date. Check the zone and the dates. | | `product_not_available` | 422 | A product is not offered on that date, is not live, or cannot be ordered. Check the catalog. | | `order_limits_not_met` | 422 | The order is below or above the vendor's limits on items or value. Change the items. | | `vendor_not_allowed_for_customer` | 422 | The customer's account is limited to certain vendors and this is not one of them. Offer another vendor. | | `invalid_time_range` | 422 | The open times range is empty, backwards or longer than 31 days. Fix `from` and `to`. | | `measurement_required` | 422 | A first health profile save has no `general_health_data`. Add it. See [Health profiles](/docs/care/health-profiles). | | `invalid_api_key` | 401 | The key is missing, malformed, unknown, revoked or expired. All look the same. Check the key and header. | | `scope_not_granted` | 403 | The key lacks the scope the route needs. See [Scopes](/docs/concepts/scopes). | | `connection_scope_not_granted` | 403 | The customer or patient did not approve the connection scope this needs. See [Connections](/docs/concepts/connections). | | `company_suspended` | 403 | Nurish'd suspended your company. Contact support. | | `company_archived` | 403 | Nurish'd archived your company. Contact support. | | `company_archived` | 409 | A customer or patient cannot be created or connected for an archived company. Contact support. | | `company_not_live` | 403 | A Production key was used before Nurish'd marked the company Live. | | `test_mode_only` | 403 | A Sandbox test helper was called with a Production key. Use a Sandbox key. | | `not_found` | 404 | The object does not exist, or it belongs to another company or environment. | | `health_profile_not_found` | 404 | The patient has no health profile yet. Create it with an update that has `general_health_data`. | | `method_not_allowed` | 405 | The route does not allow this HTTP method. | | `connection_not_active` | 409 | The connection is not `active`, so the action is refused. Read the connection. | | `measurement_too_recent` | 409 | The patient has a measurement from the last 24 hours. Send the update without `general_health_data`. | | `webhook_endpoint_limit_reached` | 409 | A company has at most 10 webhook endpoints per environment. Delete one first. | | `order_conflict` | 409 | The order cannot be placed in its current state. Read the customer and the connection, then decide. | | `external_id_conflict` | 409 | The `external_id` already belongs to a customer or patient with a different email. Keep using the first id. | | `person_already_connected` | 409 | The email is already connected under a different `external_id`. Keep using the first id. | | `booking_not_completable` | 409 | The test helper was called for a booking that was canceled or is already completed. Use another test booking. | | `payment_method_required` | 409 | The patient has no card saved, so no visit can be booked. Save one first. See [Saving a card](/docs/care/saving-a-card). | | `payment_method_setup_incomplete` | 409 | The card form has not confirmed the card yet. Finish it with Stripe.js, then call confirm again. | | `agreements_not_signed` | 409 | The patient has not signed the agreements a visit needs. Send them to a fresh connect URL. | | `service_not_bookable` | 409 | The service cannot be booked online, or the specialist or the service does not exist. Offer another service. | | `not_licensed_here` | 409 | The specialist cannot serve this booking yet. Offer another specialist. | | `slot_taken` | 409 | The time is no longer open. Read the open times again. | | `booking_not_cancelable` | 409 | The booking is already canceled, completed or past. Read the booking. | | `rate_limited` | 429 | You are over the limit. Wait `Retry-After` seconds. See [Rate limits](/docs/concepts/rate-limits). | | `internal_error` | 500 | Something failed on our side. | | `upstream_error` | 502 | A system we depend on failed. | | `upstream_unavailable` | 503 | A system we depend on is unavailable. | | `upstream_timeout` | 504 | A system we depend on took too long. | ## Ids An id in a path, the `vendor` query parameter and the order field `order_vendor` take letters, digits, hyphens, underscores and dots, start with a letter, digit, hyphen or underscore, and have at most 200 characters (`^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$`). An id that does not fit is a `422 validation_error`. ## Which errors are safe to retry | Retry | Codes | How | | ------------------ | ------------------------------------------------------------------------------ | ---------------------------------------------------------- | | Yes, after waiting | `rate_limited` | Wait `Retry-After` seconds. | | Yes, with backoff | `upstream_error`, `upstream_unavailable`, `upstream_timeout`, `internal_error` | Exponential backoff with jitter, and a cap of a few tries. | | No | Every other code | The same request fails the same way. Fix it first. | Retry `GET` calls freely. Be careful with writes: if a `POST` to `create` times out, you may not know whether it worked. For customers and patients, calling create again with the same `external_id` returns the same one. An order with the same `reference`, or a booking for the same patient, specialist and start, returns the first one. See [Customers](/docs/meals/customers), [Orders](/docs/meals/orders) and [Booking a visit](/docs/care/booking-a-visit). ```javascript async function call(url, init, tries = 4) { for (let i = 0; i < tries; i++) { const res = await fetch(url, init); if (res.ok) return res; const retryable = [429, 500, 502, 503, 504].includes(res.status); if (!retryable || i === tries - 1) { const body = await res.json().catch(() => ({})); throw new Error( `${body.error?.code} request_id=${body.error?.request_id}`, ); } const wait = Number(res.headers.get('Retry-After')) || 2 ** i; await new Promise((r) => setTimeout(r, wait * 1000)); } } ``` ## Request ids Every answer, success or error, carries `X-Request-Id`. Error bodies repeat it as `request_id`. Log it with every failed call. It lets Nurish'd find exactly one call. ## Next - [Rate limits](/docs/concepts/rate-limits): handle `429` well. - [Authentication](/docs/concepts/authentication): fix `invalid_api_key`. - [Support](/docs/resources/support): what to send with a request id. --- # Rate limits How many calls a key may make per minute, the headers that tell you where you stand, and how to handle a 429. You will know your limit, read it from response headers, and back off correctly when you hit it. ## The limits Every limit is counted for each API key. There are four. | Limit | Sandbox | Production | | -------------------------------- | --------------------- | --------------------- | | Calls per minute | 25 by default | 100 by default | | Burst | 120 in any 10 seconds | 600 in any 10 seconds | | Report routes and the event list | 10 per minute | 30 per minute | | Calls in progress at once | 10 | 50 | **Calls per minute.** Nurish'd sets this number per company, so yours may differ. `GET /developer/v1/key/get/document` returns it in `rate_limit_per_minute`. The console shows it too. To ask for more, email `hello@nurishd.io`. **Burst.** Calls you do not use add up. A key that was quiet can go above its calls per minute for a moment, up to the burst line. **Report routes and the event list.** These four routes have their own, lower line: - `GET /care/v1/report/query/documents` - `GET /care/v1/report/{report_id}/get/document` - `GET /care/v1/report/{report_id}/section/{section_id}/file/get/document` - `GET /developer/v1/event/query/documents` A call to one of them counts against this line and against your calls per minute. **Calls in progress at once.** This counts the calls Nurish'd is still answering for your key. Wait for answers before you send more, or cap your workers below the number. Passing any of the four answers `429 rate_limited` with a `Retry-After` header. ## Headers Every authenticated answer, errors included, carries: | Header | Meaning | | --------------------- | ----------------------------------------------------------------------------- | | `RateLimit-Limit` | Calls per minute for this key. | | `RateLimit-Remaining` | Calls you can make right now. After a quiet moment it can be above the limit. | | `Retry-After` | Seconds to wait. Only on a `429`. | On a report route and on the event list, both `RateLimit` headers describe that route's own line. A `401` carries none of these, because the key could not be identified. ```http HTTP/1.1 429 Too Many Requests RateLimit-Limit: 25 RateLimit-Remaining: 0 Retry-After: 12 X-Request-Id: req-0001 Content-Type: application/json {"error": {"code": "rate_limited", "message": "Too many requests.", "request_id": "req-0001"}} ``` ## Handle a 429 1. Stop sending calls with that key. 2. Wait `Retry-After` seconds. 3. Retry the call. ```python import os import time import requests def get(url, **kwargs): for _ in range(4): res = requests.get(url, headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, **kwargs) if res.status_code != 429: return res time.sleep(int(res.headers.get("Retry-After", "5"))) return res ``` ## Stay under the limit - Read `RateLimit-Remaining` and slow down before it reaches zero. - Do not send many calls at the same moment. Keep the calls in progress under the limit. - Fetch a report once and keep it. Report routes have the lowest limit. - Use `size` up to 50 to fetch fewer pages. See [Pagination](/docs/concepts/pagination). - Poll events no more often than you need. Use a cursor on `created`. See [Events](/docs/events/events). - Cache catalog data that rarely changes, such as vendors and products. - Spread work from several services over several keys only if each has its own job. Limits are per key. ## Next - [Pagination](/docs/concepts/pagination): fewer calls per list. - [Errors](/docs/concepts/errors): which errors to retry. - [Events](/docs/events/events): poll without wasting calls. --- # Pagination and filters Page through lists with page and size, and narrow them with single-word filters. You will page through any list and narrow it with filters. ## Parameters Every list route takes `page` and `size`. | Parameter | Default | Rule | | --------- | ------- | ------------- | | `page` | 1 | From 1. | | `size` | 10 | From 1 to 50. | ## The answer ```json { "data": [ { "vendor_id": "vendor-0001", "vendor_name": "Green Table Kitchen" } ], "total_pages": 3, "total": 25, "page": 1, "size": 10, "has_next": true, "has_previous": false } ``` `data` holds the items (trimmed here). The other fields describe the page. Stop when `has_next` is `false`. ## Walk every page ```bash curl "https://api.dev.nurishd.ca/meals/v1/vendor/query/documents?page=2&size=50" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript async function allVendors() { const vendors = []; for (let page = 1; ; page++) { const res = await fetch( `https://api.dev.nurishd.ca/meals/v1/vendor/query/documents?page=${page}&size=50`, { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY } }, ); const body = await res.json(); vendors.push(...body.data); if (!body.has_next) return vendors; } } ``` ```python import os import requests def all_vendors(): vendors, page = [], 1 while True: res = requests.get( "https://api.dev.nurishd.ca/meals/v1/vendor/query/documents", params={"page": page, "size": 50}, headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) body = res.json() vendors.extend(body["data"]) if not body["has_next"]: return vendors page += 1 ``` ## Filters Filters are single words in the query string, such as `name`, `type`, `status`, `from` and `to`. Each route lists its own. Filter values are the internal values of the resource, for example `type=Meal` or `status=meeting_cancelled`. Check the spelling and the values against the [API reference](/reference). | Route | Filters | | ---------------------------------------------------------- | ----------------------------------------------- | | `GET /meals/v1/vendor/query/documents` | `name` | | `GET /meals/v1/vendor/{vendor_id}/menu/query/documents` | `status` | | `GET /meals/v1/vendor/{vendor_id}/product/query/documents` | `name`, `type`, `collection`, `tag` | | `GET /meals/v1/zone/query/documents` | `city`, `state`, `country` (required), `vendor` | | `GET /developer/v1/event/query/documents` | `type`, `from`, `to` | A filter with a bad value answers `422 validation_error`. Combine filters freely. > **Note.** Lists have a default order, such as newest first for events. A change to the default order or page size is a breaking change, so you can rely on it within a version. ## Next - [Events](/docs/events/events): list and filter events. - [Catalog](/docs/meals/catalog): filters for products and menus. - [Rate limits](/docs/concepts/rate-limits): fewer calls with a larger `size`. --- # Versioning How the version in the path works, what counts as a breaking change, and how long an old version keeps working. You will know what can change under you, what cannot, and how much warning you get. ## The version is in the path Every path starts with a product and a version. ```text /meals/v1/... /care/v1/... /developer/v1/... ``` Each product moves on its own. A new `/care/v2` does not move `/meals/v1`. ## Not breaking These ship into `v1` at any time: - A new endpoint. - A new optional input. - A new field in an answer. - A new event type. - A new error code for a new failure. Write your code to ignore fields and event types it does not know. Do not fail on an unknown enum value, and do not reject an answer for having an extra field. ## Breaking These ship only in a new version, so they never change under `v1`: - Removing or renaming a field. - Changing the type of a field. - Making an input required. - Changing what a status or an error code means. - Changing the default sort or the default page size. ## When a new version ships When `v2` of a product ships, its `v1` keeps working for at least six months. - Nurish'd tells you by email and in the [changelog](/docs/resources/changelog). - Every `v1` answer then carries a `Deprecation` header with the end date. - You move when you are ready, inside the six months. ```http HTTP/1.1 200 OK Deprecation: Wed, 30 Jun 2027 00:00:00 GMT ``` The date above is an example. Log the header when you see it, and alert on it so a deprecation does not surprise you. ## Next - [Changelog](/docs/resources/changelog): what has shipped. - [Errors](/docs/concepts/errors): unknown codes and how to handle them. - [API reference](/reference): the current operations. --- # Connections A connection is a customer's or patient's consent for your company to act for them; learn its statuses, scopes and return URLs. You will understand how a customer or patient agrees that your company may act for them, and how to follow that agreement safely. ## The connection is the consent Your company cannot act for a person until they say so. The person approves on a Nurish'd page, not on yours. The record of that approval is a connection. 1. You create the customer (meals) or patient (care). The answer holds a `connect_url`. 2. You send the person to the `connect_url` as a full page or a new tab. Never open it in a frame or a web view. The page refuses to render inside another site. 3. The person approves or declines on the Nurish'd page. 4. Nurish'd sends them back to your return URL, if you gave one. 5. You learn the result from an event or by reading the connection. The `connect_url` is valid for 24 hours and works once. Create again with the same `external_id` to get a fresh link. ## Statuses | Status | Meaning | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pending` | Waiting for the person to decide. Nothing can be done for them yet. | | `active` | The person approved. | | `declined` | The person declined. Start again with a fresh link. | | `revoked` | The connection ended. The person, your company or Nurish'd can revoke. `revoked_by` says who: `patient` (the customer or patient), `partner` (your company) or `admin`. | A connection that is not `active` refuses actions with `409 connection_not_active`. A care connection and a meals connection have the same shape. `user` is the id of the customer or patient. ```json { "connection_id": "connection-0001", "company_id": "company-0001", "user": "6f1c0d2e-0000-4000-8000-000000000101", "external_id": "customer-1001", "status": "active", "scopes": ["meals.orders"], "created_at": "2026-11-30T15:04:05Z", "approved_at": "2026-11-30T15:10:12Z", "revoked_at": null, "revoked_by": null } ``` ## Connection scopes A connection carries what the person approved. | Connection scope | What the person approves | Company scope it needs | | --------------------- | ---------------------------------------------------- | ----------------------------------------------- | | `meals.orders` | Place meal orders for them and see the orders placed | `order:write` | | `care.bookings` | Book and manage visits | `booking:write` | | `care.reports` | Receive reports of visits you book | `report:read` | | `care.health-profile` | Read and update the health profile | `health-profile:read` or `health-profile:write` | If a call needs a connection scope the person did not approve, it answers `403 connection_scope_not_granted`. For care, the patient is asked to allow every care scope your key can use when you create the patient. Care scopes need a signed BAA on your company, and the patient signs the health privacy agreement and the telehealth consent on the connect page. See [BAA handling](/docs/care/baa). ## Return URLs You can pass a `return_url` when you create a customer or a patient. The person goes there after the approval page. - Return URLs must be allowlisted in the console. Owners and admins manage them. See [Company settings](/docs/console/company-settings). - A `return_url` that is not on the list answers `422 validation_error`. - The return URL carries `connection_id` and `status`. > **Warning.** Never trust the `status` in the return URL. Anyone can edit a URL. Trust the `connection.approved` event, or read the connection with `GET /meals/v1/connection/{connection_id}/get/document` (meals) or `GET /care/v1/connection/{connection_id}/get/document` (care). ```text https://shop.example.com/nurishd/return?connection_id=connection-0001&status=approved ``` ## One external id per person A customer or patient is known to your company under one `external_id`. Create refuses two requests with `409` and creates nothing: `external_id_conflict` when the `external_id` already belongs to someone with a different email, and `person_already_connected` when the email is already connected under a different `external_id`. Keep using the first id. ## Asking for more scopes later Create again with the same `external_id` and a scope the connection does not hold. The connection goes back to `pending` with the old and new scopes together, and you get a fresh link. Nothing works for that person until they approve again. ## Events | Event | When | | --------------------- | --------------------- | | `connection.approved` | The person approved. | | `connection.declined` | The person declined. | | `connection.revoked` | The connection ended. | Each event carries the connection id. See [Events](/docs/events/events). ## Revoke Your company revokes a connection with `PUT /meals/v1/connection/{connection_id}/revoke/document` (meals) or `PUT /care/v1/connection/{connection_id}/revoke/document` (care). The person can revoke in their Nurish'd account. Revoking raises `connection.revoked`. ## Next - [Customers](/docs/meals/customers): create a customer and follow the connection. - [Connecting a patient](/docs/care/connecting-a-patient): the same flow for care. - [Events](/docs/events/events): react to connection events. - [Company settings](/docs/console/company-settings): register return URLs. --- # Catalog Find a delivery zone for a place, list a vendor's products and read what a zone offers on a delivery date. You will find which vendors deliver to a place, list a vendor's products, and read what a zone offers on a delivery date. Every route here is a `GET` and needs the `catalog:read` scope. ## The pieces | Object | What it is | | ------------- | ----------------------------------------------------------------------------------------- | | Vendor | A kitchen you can order from. Vendors that are not live or were retired are never listed. | | Menu | A vendor's menu, with product ids by meal slot. | | Product | A meal, bulk item or misc item. Prices are in cents. | | Zone | A delivery area of one vendor. It covers a city, a province or a country. | | Delivery date | A date a zone delivers on, with a menu and a list of products. | ## Walk through: from a place to a delivery date ### 1. Find the zones that serve a city `GET /meals/v1/zone/query/documents` needs `city`, `state` (two capital letters) and `country` (two capital letters). It returns the best matching zone of each vendor that delivers there. The place is compared exactly with what the zone holds: `city`, `state` and `country` must match letter for letter, and letter case counts (`Toronto` does not find a zone stored as `toronto`). Add `vendor` to ask about one vendor. An empty page then means that vendor does not deliver there. ```bash curl "https://api.dev.nurishd.ca/meals/v1/zone/query/documents?city=Mississauga&state=ON&country=CA" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const params = new URLSearchParams({ city: 'Mississauga', state: 'ON', country: 'CA', }); const res = await fetch( `https://api.dev.nurishd.ca/meals/v1/zone/query/documents?${params}`, { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const zones = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/meals/v1/zone/query/documents", params={"city": "Mississauga", "state": "ON", "country": "CA"}, headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) zones = res.json() ``` ```json { "data": [ { "zone_id": "zone-0001", "vendor": "vendor-0001", "zone_city": "Mississauga", "zone_state": "ON", "zone_country": "CA", "zone_currency": "CAD", "zone_delivery_days": [ { "delivery_day": "Tuesday", "delivery_day_cutoff": 3, "delivery_day_cutoff_hour": 12, "delivery_day_cutoff_minute": 0, "fulfillment_days": 2, "delivery_fee": 799, "free_delivery_threshold": 10000 } ] } ], "total_pages": 1, "total": 1, "page": 1, "size": 10, "has_next": false, "has_previous": false } ``` `delivery_fee` and `free_delivery_threshold` are in cents, in the zone's `zone_currency`. `delivery_day_cutoff` is how many days before the delivery date ordering closes. The cut-off hour and minute are in the vendor's timezone. A zone limited to a province has `zone_city: null`. A zone for a whole country has no city and no province. ### 2. Read the vendor `GET /meals/v1/vendor/{vendor_id}/get/document` adds the long description, timezone, address and support contact that the list leaves out. ### 3. List the vendor's products `GET /meals/v1/vendor/{vendor_id}/product/query/documents` takes the filters `name`, `type` (`Meal`, `Bulk`, `Misc`), `collection` (`Breakfast`, `Lunch`, `Dinner`, `Drink`, `Snack`, `Supplement`, `Sauce`) and `tag` (a tag id). ```bash curl "https://api.dev.nurishd.ca/meals/v1/vendor/vendor-0001/product/query/documents?type=Meal&collection=Lunch&size=2" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const url = 'https://api.dev.nurishd.ca/meals/v1/vendor/vendor-0001/product/query/documents?type=Meal&collection=Lunch&size=2'; const res = await fetch(url, { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }); const products = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/meals/v1/vendor/vendor-0001/product/query/documents", params={"type": "Meal", "collection": "Lunch", "size": 2}, headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) products = res.json() ``` ```json { "data": [ { "product_id": "product-0001", "vendor": "vendor-0001", "product_name": "Chicken and rice bowl", "product_title": "Chicken and rice bowl", "product_sku": "CRB-001", "product_type": "Meal", "product_meal_collections": ["Lunch"], "tags": [], "product_price": 1299, "product_images": [], "product_logo_image": null, "product_unit_label": "Box", "product_use_by": 5, "product_contains": "Contains: none", "product_nutrition": { "total_weight": { "quantity": 350, "unit": "g" }, "per_serving_size": { "quantity": 350, "unit": "g" }, "total_servings": 1, "nutrition": { "carbohydrates": { "added_sugars__G": 4, "dietary_fiber__G": 5, "total_sugars__G": 9 }, "cholesterol": { "cholesterol__MG": 85 }, "fats": { "monounsaturated_fat__G": 8.1, "omega_3_fatty_acids__G": 2.1, "omega_6_fatty_acids__G": 1.6, "polyunsaturated_fat__G": 4.2, "saturated_fat__G": 3.5, "trans_fat__G": 0 }, "macros": { "total_calories__KCAL": 520, "total_fat__G": 14, "total_carbohydrate__G": 62, "total_protein__G": 38 }, "minerals": { "calcium__MG": 70, "chromium__MCG": 12, "copper__MG": 0.4, "iodine__MCG": 30, "iron__MG": 2.4, "magnesium__MG": 95, "manganese__MG": 1.5, "molybdenum__MCG": 60, "phosphorus__MG": 410, "potassium__MG": 820, "selenium__MCG": 48, "zinc__MG": 1.8 }, "other_nutrients": { "alcohol__PERCENT": 0, "caffeine__MG": 0, "water_content__G": 210 }, "sodium": { "sodium__MG": 640 }, "vitamins": { "biotin__MCG": 9, "choline__MCG": 160000, "folate__MCG": 140, "niacin__MCG": 12000, "pantothenic_acid__MCG": 1800, "riboflavin__MCG": 380, "thiamin__MCG": 450, "vitamin_a__MCG": 120, "vitamin_b12__MCG": 4.2, "vitamin_b6__MCG": 900, "vitamin_c__MCG": 38000, "vitamin_d__MCG": 11, "vitamin_e__MCG": 2600, "vitamin_k__MCG": 85 } }, "label_ingredient_listing": "Chicken, rice, broccoli, olive oil." } } ], "total_pages": 1, "total": 1, "page": 1, "size": 2, "has_next": false, "has_previous": false } ``` The list leaves out `product_description` and `product_features`, and the creation and update times. Read one product with `GET /meals/v1/vendor/{vendor_id}/product/{product_id}/get/document` to get them. `product_price` is in cents. `product_nutrition` holds `total_weight`, `per_serving_size`, `total_servings`, `nutrition` and `label_ingredient_listing`. `nutrition` is `null` when the vendor has no nutrition facts for the product. When it is present it groups values by `macros`, `fats`, `cholesterol`, `sodium`, `carbohydrates`, `minerals`, `vitamins` and `other_nutrients`. Each value name ends with its unit, for example `total_calories__KCAL`, `sodium__MG` or `vitamin_d__MCG`. The groups and values the spec lists are all required when `nutrition` is present. ### 4. List the delivery dates of a zone `GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documents` needs `from` and `to` as `YYYY-MM-DD`. `to` can be at most 60 days after `from` and at most 60 days from now, otherwise it answers `400`. Only the day is accepted: a value with a time is refused. Each date is the instant of midnight at the start of the delivery day in the vendor's timezone (`vendor_timezone` on the vendor), written in UTC, oldest first. For a vendor in Central time, the delivery day 2026-11-24 is listed as `2026-11-24T06:00:00Z`. A date is listed only when the zone delivers that weekday, ordering is still open, a menu is in production, and it is not a blackout date. ```bash curl "https://api.dev.nurishd.ca/meals/v1/vendor/vendor-0001/zone/zone-0001/delivery-date/query/documents?from=2026-12-01&to=2026-12-14" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const url = 'https://api.dev.nurishd.ca/meals/v1/vendor/vendor-0001/zone/zone-0001/delivery-date/query/documents?from=2026-12-01&to=2026-12-14'; const res = await fetch(url, { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }); const dates = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/meals/v1/vendor/vendor-0001/zone/zone-0001/delivery-date/query/documents", params={"from": "2026-12-01", "to": "2026-12-14"}, headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) dates = res.json() ``` ```json { "valid_delivery_dates": ["2026-12-01T05:00:00Z", "2026-12-08T05:00:00Z"] } ``` ### 5. Read one delivery date `GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{date}/get/document` takes the delivery day as `YYYY-MM-DD` in the path: the date part of a `valid_delivery_dates` value, so `2026-11-24` for `2026-11-24T06:00:00Z`. The full value with its time is not accepted. It says when ordering closes, which menu is in production and which products you can order. ```bash curl https://api.dev.nurishd.ca/meals/v1/vendor/vendor-0001/zone/zone-0001/delivery-date/2026-12-01/get/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const url = 'https://api.dev.nurishd.ca/meals/v1/vendor/vendor-0001/zone/zone-0001/delivery-date/2026-12-01/get/document'; const res = await fetch(url, { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }); const day = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/meals/v1/vendor/vendor-0001/zone/zone-0001/delivery-date/2026-12-01/get/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) day = res.json() ``` ```json { "vendor": "vendor-0001", "vendor_zone": "zone-0001", "input_query_date": "2026-12-01T05:00:00Z", "is_given_date_blackout": false, "blackout_date": null, "production_date": "2026-11-29T05:00:00Z", "delivery_date": "2026-12-01T05:00:00Z", "order_cutoff_date": "2026-11-28T17:00:00Z", "menu": "menu-0001", "additional_product_ids": null, "all_unique_product_ids": ["product-0001", "product-0002"] } ``` The zone cannot deliver on a date when `menu` is `null` and `all_unique_product_ids` is empty. That is the case for a blackout date (`is_given_date_blackout` is `true`), a date with no menu and a weekday the zone does not deliver on. A weekday the zone does not deliver on also has no `production_date`, `delivery_date` or `order_cutoff_date`. The vendor, zone, blackout date and menu are IDs, not objects. > **Note.** In Production, a key sees no vendors until Nurish'd enables them for your company. A vendor that is not enabled for your company answers `404 not_found` when you place an order. Ask Nurish'd to enable vendors for your company. ## Menus `GET /meals/v1/vendor/{vendor_id}/menu/query/documents` lists a vendor's menus. Filter with `status`: `in_production`, `upcoming`, `expired` or `not_in_production`. `GET /meals/v1/vendor/{vendor_id}/menu/{menu_id}/get/document` returns one menu with its product ids by slot: `breakfast_items`, `lunch_items`, `dinner_items`, `snacks_items`, `supplements_items`, `drinks_items` and `misc_items`. A menu has `menu_id`, `menu_name`, `menu_status`, `menu_production_start_date` and `menu_production_end_date`. A vendor, menu or product that does not exist, is not live, or was retired answers `404 not_found`. ## Next - [Customers](/docs/meals/customers): connect a customer to your company. - [Pagination](/docs/concepts/pagination): lists and filters. - [Orders](/docs/meals/orders): place an order for a connected customer. --- # Customers Create a meals customer, send them to the connect URL, read the connection and revoke it. You will create a customer, send them to approve the connection, follow the result, and end the connection when you need to. Creating a customer and revoking a connection need the `order:write` scope. Reading a customer or a connection needs `order:read`. ## Create a customer `POST /meals/v1/customer/create/document` creates a customer and starts a connection with them. Nothing can be ordered for a customer until they approve. | Field | Required | Notes | | ------------- | -------- | -------------------------------------------------------------------------------------------- | | `external_id` | Yes | Your own id for the customer, 1 to 200 characters. | | `email` | Yes | The approval page sends its code to the address on the customer's Nurish'd account. | | `first_name` | Yes | | | `last_name` | Yes | | | `return_url` | No | Where the customer goes after the approval page. Must be one of your registered return URLs. | ```bash curl -X POST https://api.dev.nurishd.ca/meals/v1/customer/create/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "external_id": "customer-1001", "email": "ada.lovelace@example.com", "first_name": "Ada", "last_name": "Lovelace", "return_url": "https://shop.example.com/nurishd/return" }' ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/meals/v1/customer/create/document', { method: 'POST', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ external_id: 'customer-1001', email: 'ada.lovelace@example.com', first_name: 'Ada', last_name: 'Lovelace', return_url: 'https://shop.example.com/nurishd/return', }), }, ); const customer = await res.json(); ``` ```python import os import requests res = requests.post( "https://api.dev.nurishd.ca/meals/v1/customer/create/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, json={ "external_id": "customer-1001", "email": "ada.lovelace@example.com", "first_name": "Ada", "last_name": "Lovelace", "return_url": "https://shop.example.com/nurishd/return", }, ) customer = res.json() ``` The answer: ```json { "user": "6f1c0d2e-0000-4000-8000-000000000101", "connection": { "connection_id": "connection-0001", "company_id": "company-0001", "user": "6f1c0d2e-0000-4000-8000-000000000101", "external_id": "customer-1001", "status": "pending", "scopes": ["meals.orders"], "created_at": "2026-11-30T15:04:05Z", "approved_at": null, "revoked_at": null, "revoked_by": null }, "connect_url": "https://app.nurishd.ca/connect/abc123", "connect_url_expires_at": "2026-12-01T15:04:05Z" } ``` The customer's id is `user`. Use it in the customer routes and as `user` when you place an order. The connection's id is `connection.connection_id`. Calling create again with the same `external_id` returns the same customer and a fresh link. The answer never says whether the email already had a Nurish'd account. A customer is known to your company under one `external_id`. Two requests are refused with `409` and create nothing: | Code | When | | -------------------------- | ----------------------------------------------------------------------- | | `external_id_conflict` | The `external_id` already belongs to a customer with a different email. | | `person_already_connected` | The email is already connected under a different `external_id`. | To change the id you use for a customer, keep using the first one. ## Send the customer to the connect URL Send the customer to `connect_url` as a full page or a new tab. Never open it in a frame or a web view. The link is valid for 24 hours and works once. In the Sandbox, no email is sent. The connect page accepts the fixed code `424242`. See [Environments](/docs/get-started/environments). ## Follow the connection Do not trust the `status` in the return URL. Do one of these: - Wait for the `connection.approved` event. See [Events](/docs/events/events). - Read the connection: ```bash curl https://api.dev.nurishd.ca/meals/v1/connection/connection-0001/get/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/meals/v1/connection/connection-0001/get/document', { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const connection = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/meals/v1/connection/connection-0001/get/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) connection = res.json() ``` ```json { "connection_id": "connection-0001", "company_id": "company-0001", "user": "6f1c0d2e-0000-4000-8000-000000000101", "external_id": "customer-1001", "status": "active", "scopes": ["meals.orders"], "created_at": "2026-11-30T15:04:05Z", "approved_at": "2026-11-30T15:10:12Z", "revoked_at": null, "revoked_by": null } ``` `GET /meals/v1/customer/{customer_id}/get/document` returns the customer and the connection. Its `connect_url` and `connect_url_expires_at` are always `null`. Call create again for a fresh link. ## Revoke the connection `PUT /meals/v1/connection/{connection_id}/revoke/document` ends the connection. Nothing can be ordered for the customer afterwards. It raises a `connection.revoked` event. A connection that is already revoked or declined answers `409 connection_not_active`. ```bash curl -X PUT https://api.dev.nurishd.ca/meals/v1/connection/connection-0001/revoke/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/meals/v1/connection/connection-0001/revoke/document', { method: 'PUT', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const connection = await res.json(); ``` ```python import os import requests res = requests.put( "https://api.dev.nurishd.ca/meals/v1/connection/connection-0001/revoke/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) connection = res.json() ``` The answer is the connection with `status` set to `revoked`, `revoked_at` set and `revoked_by` set to `partner`. To connect again, call create with the same `external_id` and send the customer to the new `connect_url`. ## Next - [Connections](/docs/concepts/connections): statuses, scopes and return URLs. - [Events](/docs/events/events): `connection.approved` and friends. - [Saving a card](/docs/meals/saving-a-card): save a card to the customer's account. - [Orders](/docs/meals/orders): place an order for a connected customer. --- # Saving a card Save a card to a connected customer's Nurish'd account with Stripe.js, and list the saved cards. You will save a card to a customer's Nurish'd account, confirm it with Stripe.js on your own page, and list the saved cards. The flow is the same as for a patient. [Saving a card](/docs/care/saving-a-card) explains each step and the Stripe.js code in full. This page lists the meals routes. A saved card lets the customer pay for orders you place for them without typing the card in each time. How an order is paid is on [Orders](/docs/meals/orders). Starting and confirming need the `order:write` scope. Listing needs `order:read`. The customer must have an `active` connection that allows `meals.orders`. Nurish'd Connect keeps no record of card numbers: the customer types the card into Stripe's own form on your page. > **Warning.** The card is saved to the customer's Nurish'd account and may be charged for orders the customer confirms. Tell the customer so before they type the card in. ## Step 1: start the setup `POST /meals/v1/customer/{customer_id}/payment-method/setup/create/document` takes no body. `customer_id` is the id from the create-customer answer. ```bash curl -X POST https://api.dev.nurishd.ca/meals/v1/customer/6f1c0d2e-0000-4000-8000-000000000101/payment-method/setup/create/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const customerId = '6f1c0d2e-0000-4000-8000-000000000101'; const res = await fetch( `https://api.dev.nurishd.ca/meals/v1/customer/${customerId}/payment-method/setup/create/document`, { method: 'POST', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const setup = await res.json(); ``` ```python import os import requests customer_id = "6f1c0d2e-0000-4000-8000-000000000101" res = requests.post( f"https://api.dev.nurishd.ca/meals/v1/customer/{customer_id}/payment-method/setup/create/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) setup = res.json() ``` ```json { "id": "seti_example", "client_secret": "seti_example_secret_example", "status": "requires_payment_method", "stripe_publishable_key": "pk_test_example" } ``` `stripe_publishable_key` is `null` when Stripe is not configured yet. Calling start again returns the same open setup while it is less than a day old. Never log `client_secret`. ## Step 2: confirm the card in the browser Send `stripe_publishable_key` and `client_secret` to your page and call `stripe.confirmCardSetup` there. The snippet is in [Saving a card](/docs/care/saving-a-card). It runs in the browser, never on your server. ## Step 3: record the card `PUT /meals/v1/customer/{customer_id}/payment-method/setup/{setup_id}/confirm/document` takes no body. `setup_id` is the `id` of the start answer. ```bash curl -X PUT https://api.dev.nurishd.ca/meals/v1/customer/6f1c0d2e-0000-4000-8000-000000000101/payment-method/setup/seti_example/confirm/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( `https://api.dev.nurishd.ca/meals/v1/customer/${customerId}/payment-method/setup/${setup.id}/confirm/document`, { method: 'PUT', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const card = await res.json(); ``` ```python setup_id = setup["id"] res = requests.put( f"https://api.dev.nurishd.ca/meals/v1/customer/{customer_id}/payment-method/setup/{setup_id}/confirm/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) card = res.json() ``` ```json { "id": "pm_example", "card": { "brand": "visa", "last4": "4242", "exp_month": 12, "exp_year": 2030 }, "is_default": true } ``` When the customer had no default card, the saved card becomes their default and the answer says `is_default: true`. A customer who already has a default card keeps it, and the answer says `is_default: false`. Calling confirm again for the same setup is safe. ## List saved cards `GET /meals/v1/customer/{customer_id}/payment-method/query/documents` returns the saved cards, at most 10, in one page. A customer with no card gets an empty `data` list. The customer can also add, remove and choose cards in their own account, so the list can change without you. ```bash curl https://api.dev.nurishd.ca/meals/v1/customer/6f1c0d2e-0000-4000-8000-000000000101/payment-method/query/documents \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` The answer has the same shape as the care list: `data` holds cards with `id`, `card` (`brand`, `exp_month`, `exp_year` and `last4`) and `is_default`, next to the page fields. `is_default` is `true` for the customer's default card. ## Errors See [Errors](/docs/concepts/errors) for the shape. | Status and code | What it means for you | | ------------------------------------- | -------------------------------------------------------------------------------------- | | `404 not_found` | The customer has no meals connection with your company, or the setup is not theirs. | | `403 connection_scope_not_granted` | The customer did not allow orders. | | `403 scope_not_granted` | The key lacks `order:write` or, for the list, `order:read`. | | `409 connection_not_active` | The connection is `pending` or was revoked. Read the connection. | | `409 payment_method_setup_incomplete` | Confirm only: the card form has not confirmed the card yet. Finish step 2, then retry. | ## Next - [Orders](/docs/meals/orders): place an order for a connected customer. - [Customers](/docs/meals/customers): connect the customer first. - [Saving a card for a patient](/docs/care/saving-a-card): the full explanation. --- # Orders Place a meal order for a connected customer, take the payment with Stripe.js, and read orders and order events. You will place an order for a connected customer, confirm the payment on your own page, and follow the order until it is paid and fulfilled. Placing an order needs the `order:write` scope. Listing and reading orders needs `order:read`. The customer's connection must be `active` and carry `meals.orders`. See [Customers](/docs/meals/customers). ## Place an order `POST /meals/v1/order/create/document` places an order to be delivered to an address on a delivery date. Take the vendor, product ids and delivery dates from the [Catalog](/docs/meals/catalog). | Field | Required | Notes | | ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------- | | `user` | Yes | The customer id, as create answered it. | | `order_vendor` | Yes | The vendor id: letters, digits, hyphens and underscores, up to 200 characters. | | `order_delivery_date` | Yes | `YYYY-MM-DD`, the date part of a `valid_delivery_dates` value. No time of day. Must be a day the zone offers. | | `order_shipping_address` | Yes | The address, with the limits below. `line2` is optional. | | `line_items` | Yes | 1 to 50 objects with `line_item_product_id` and `line_quantity` (at least 1). A product can appear only once. | | `order_contact_email` | Yes | The email the kitchen and the courier reach the customer at. | | `order_contact_phone` | Yes | The phone number has its country code, such as `+14165550123`. At most 20 characters. | | `order_customer_notes` | No | Notes for the kitchen, up to 500 characters. | | `reference` | No | Your own reference, 1 to 200 characters. See below. | | `metadata` | No | Your own key-value data, at most 10 pairs of up to 100 characters. Returned as you sent it. | The address (`OrderShippingAddressInput`) has these limits. A value that breaks one answers `422 validation_error` naming the field. | Field | Required | Limit | | ------------- | -------- | --------------------------------------------------------- | | `line1` | Yes | Up to 200 characters. `$`, `{` and `}` are not accepted. | | `line2` | No | Up to 200 characters. `$`, `{` and `}` are not accepted. | | `city` | Yes | Up to 100 characters. `$`, `{` and `}` are not accepted. | | `state` | Yes | The province: two letters, in capitals, such as `ON`. | | `postal_code` | Yes | Letters, digits, spaces and hyphens, up to 20 characters. | | `country` | Yes | Two letters, in capitals, such as `CA`. | ```bash curl -X POST https://api.dev.nurishd.ca/meals/v1/order/create/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "user": "6f1c0d2e-0000-4000-8000-000000000101", "order_vendor": "vendor-harbour-kitchen", "order_delivery_date": "2026-04-07", "order_shipping_address": { "line1": "10 Example Street", "city": "Toronto", "state": "ON", "postal_code": "M5V 2T6", "country": "CA" }, "line_items": [ { "line_item_product_id": "product-salmon-bowl", "line_quantity": 4 }, { "line_item_product_id": "product-chicken-wrap", "line_quantity": 2 } ], "order_contact_email": "ada.lovelace@example.com", "order_contact_phone": "+14165550123", "reference": "web-order-1001" }' ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/meals/v1/order/create/document', { method: 'POST', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ user: '6f1c0d2e-0000-4000-8000-000000000101', order_vendor: 'vendor-harbour-kitchen', order_delivery_date: '2026-04-07', order_shipping_address: { line1: '10 Example Street', city: 'Toronto', state: 'ON', postal_code: 'M5V 2T6', country: 'CA', }, line_items: [ { line_item_product_id: 'product-salmon-bowl', line_quantity: 4, }, { line_item_product_id: 'product-chicken-wrap', line_quantity: 2, }, ], order_contact_email: 'ada.lovelace@example.com', order_contact_phone: '+14165550123', reference: 'web-order-1001', }), }, ); const order = await res.json(); ``` ```python import os import requests res = requests.post( "https://api.dev.nurishd.ca/meals/v1/order/create/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, json={ "user": "6f1c0d2e-0000-4000-8000-000000000101", "order_vendor": "vendor-harbour-kitchen", "order_delivery_date": "2026-04-07", "order_shipping_address": { "line1": "10 Example Street", "city": "Toronto", "state": "ON", "postal_code": "M5V 2T6", "country": "CA", }, "line_items": [ {"line_item_product_id": "product-salmon-bowl", "line_quantity": 4}, {"line_item_product_id": "product-chicken-wrap", "line_quantity": 2}, ], "order_contact_email": "ada.lovelace@example.com", "order_contact_phone": "+14165550123", "reference": "web-order-1001", }, ) order = res.json() ``` The answer, with the fields trimmed to the ones you use first. Amounts are in cents. ```json { "order_id": "ORD-ONE-OFF-4F7K2A9Q", "reference": "web-order-1001", "user": "6f1c0d2e-0000-4000-8000-000000000101", "order_vendor": { "vendor_id": "vendor-harbour-kitchen", "vendor_name": "Harbour Kitchen", "vendor_timezone": "America/Toronto" }, "order_financial_status": "pending", "order_fulfillment_status": "pending payment", "order_delivery_status": "pending payment", "order_currency": "CAD", "order_total_price__BEFORE_TAX_DISCOUNT_AND_SHIPPING": 5980, "order_shipping_cost": 499, "order_tax_amount": 0, "order_discount_amount": 0, "order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING": 6479, "order_delivery_date": "2026-04-07T04:00:00Z", "order_cutoff_date": "2026-04-04T19:30:00Z", "stripe_payment_intent": { "stripe_payment_intent_client_secret": "pi_example_secret_example", "stripe_payment_intent_status": "requires_payment_method" }, "stripe_publishable_key": "pk_test_example", "order_created_at": "2026-04-01T15:04:05Z", "order_paid_at": null, "line_items": null } ``` The order carries Nurish'd's own field names. `order_vendor` is the vendor as it was when the order was placed. `line_items` is `null` here and holds the items when you read one order. The three statuses use the internal values: | Field | Values | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `order_financial_status` | `draft`, `pending`, `failed payment`, `paid`, `cancelled`, `partially refunded`, `refunded`, `chargeback`. | | `order_fulfillment_status` | `draft`, `pending payment`, `not started`, `preparing meals`, `partially completed`, `completed`, `cancelled`, `do not process`. | | `order_delivery_status` | `draft`, `pending payment`, `not yet shipped`, `shipped`, `delivered`, `delivery failed`, `cancelled`, `do not process`. | The amounts are `order_total_price__BEFORE_TAX_DISCOUNT_AND_SHIPPING` (the value of the line items), `order_shipping_cost`, `order_tax_amount`, `order_discount_amount` and `order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING` (what the customer pays), all in `order_currency`. `order_service_charges` lists charges added after tax, and the total includes them. Sending the same `reference` again returns the order already placed instead of a second one, so a retry after a timeout is safe. The reference, `metadata` and the key that placed the order are kept with the order. Nurish'd takes your company and key from the API key, never from the body. > **Warning.** If the customer already started a cart for the same vendor, address zone and date in the Nurish'd app, that cart is emptied first, including any discount code or points on it. ## Take the payment The customer's card pays. The order holds what your page needs: | Field | Meaning | | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `order_financial_status` | The payment status. | | `stripe_payment_intent.stripe_payment_intent_client_secret` | The Stripe PaymentIntent client secret. Only while the payment is `pending`; otherwise `stripe_payment_intent` is `null`. | | `stripe_payment_intent.stripe_payment_intent_status` | The status of the Stripe PaymentIntent, for example `requires_payment_method`. | | `stripe_publishable_key` | The Stripe publishable key. `null` until Stripe keys are configured. | Confirm the payment on your own page with Stripe.js. This runs in the browser, never on your server. Send only the client secret and the publishable key to the page. ```javascript // Runs in the browser, with Stripe.js loaded and a card element mounted. const stripe = Stripe(publishableKey); const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret, { payment_method: { card: cardElement }, }); ``` > **Warning.** Do not treat the order as paid because your page says the card was accepted. The order is paid when `order_financial_status` is `paid` or the `order.paid` event arrives. An order that costs nothing is paid at once and has `stripe_payment_intent` set to `null`. If the customer reloads before paying, `GET /meals/v1/order/{order_id}/get/document` returns the client secret again while the payment is `pending`. > **Note.** How an order is paid is still provisional. The customer's card pays today. Who pays, the customer or your company on a statement, is not final. ## Order limits and delivery errors Before anything is placed, the order is checked against the catalog, the vendor first. A vendor that does not exist, is not live, is archived or is not enabled for your company answers `404 not_found`. Then each failure answers `422` with its own code and creates nothing. | Code | What it means for you | | --------------------------------- | ------------------------------------------------------------------------------------------------------- | | `delivery_not_available` | The vendor does not deliver to the address, or not on that date. Check the zone and the dates. | | `product_not_available` | A product is not offered on that date, is not live, or cannot be ordered. Check the catalog. | | `order_limits_not_met` | The order is below or above the vendor's limits on items or value. Change the items. | | `vendor_not_allowed_for_customer` | The customer's account is limited to certain vendors and this is not one of them. Offer another vendor. | Other answers: - `404 not_found` for an unknown customer, or for a vendor that cannot be used (see above). - `409 connection_not_active` while the customer has not approved the connection or after they revoked it. - `409 order_conflict` when the order cannot be placed in its current state. See [Errors](/docs/concepts/errors). None of these is safe to retry unchanged. ## List orders `GET /meals/v1/order/query/documents` returns a page of the orders your company placed, newest first, without their line items. Orders of a customer whose connection is no longer active are left out. | Parameter | Meaning | | -------------- | ---------------------------------------------------------------------------------------------------------------------- | | `customer` | Keep only the orders of this customer. | | `vendor` | Keep only the orders of this vendor. | | `status` | `pending`, `paid`, `fulfilled` or `canceled`. This is the stage this API records, not one of the three order statuses. | | `from`, `to` | Keep orders placed at or after, or at or before, this time (ISO 8601). | | `page`, `size` | See [Pagination](/docs/concepts/pagination). `size` is at most 50. | The stage behind `status` is updated when an order is read or when Nurish'd reports a change, so a list filter can lag behind until then. ```bash curl "https://api.dev.nurishd.ca/meals/v1/order/query/documents?status=paid&size=10" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ## Read an order `GET /meals/v1/order/{order_id}/get/document` returns one order with its `line_items`, which are `null` in lists. Each line item has `line_item_product` (`product_id`, `product_name` and `product_price`, the product as it was when the order was placed), `line_item_quantity`, `line_item_fulfilled_quantity`, `line_item_financial_status`, `line_item_fulfillment_status`, `line_item_delivery_status` and `line_item_currency`. An order that does not exist, or belongs to another company or environment, answers `404 not_found`. Once the customer revokes the connection it answers `409 connection_not_active`: you can no longer read their orders. ## Order events | Event | When | | ----------------- | ----------------------- | | `order.created` | An order was created. | | `order.paid` | An order was paid. | | `order.fulfilled` | An order was fulfilled. | | `order.shipped` | An order was shipped. | | `order.delivered` | An order was delivered. | | `order.refunded` | An order was refunded. | | `order.canceled` | An order was canceled. | Order events carry the `order` id and the `customer` id, never a `patient`. They are the same ids as `order_id` and `user`. They need the `order:read` scope to be seen. See [Events](/docs/events/events). `order.shipped` and `order.delivered` follow the order's `order_delivery_status`. `order.refunded` follows `order_financial_status` becoming `refunded` or `partially refunded`. An event can arrive late or in another order than it happened, so read the order for its present state. An order that was deleted before it was paid raises `order.canceled` and then answers `404 not_found` when you read it. The order list leaves it out. ## Next - [Customers](/docs/meals/customers): connect a customer first. - [Catalog](/docs/meals/catalog): vendors, products and delivery dates. - [Events](/docs/events/events): react to order events. --- # Connecting a patient Create a patient, send them to the connect URL, learn that they approved, read the connection and revoke it. You will create a patient, send them to approve the connection, follow the result, and end the connection when you need to. Creating a patient, reading a patient, reading a connection and revoking a connection all need the `patient:write` scope. That scope needs a signed BAA. See [BAA handling](/docs/care/baa). ## Create a patient `POST /care/v1/patient/create/document` creates a patient, or connects to the patient's existing Nurish'd account, and starts a connection with them. Nothing can be booked for a patient until they approve. | Field | Required | Notes | | --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `external_id` | Yes | Your own id for the patient, 1 to 200 characters. | | `email` | Yes | The approval page sends its code to the address on the patient's Nurish'd account. | | `first_name` | Yes | At most 100 characters. | | `last_name` | Yes | At most 100 characters. | | `date_of_birth` | Yes | `YYYY-MM-DD`, in the past. | | `address` | Yes | `line1`, `city`, `state`, `postal_code` and `country`, and `line2` if there is one. See below. | | `return_url` | No | Where the patient goes after the approval page. Must be one of your registered return URLs, otherwise the call answers `validation_error`. | The address is required: a call without one answers `422 validation_error`. A dietitian must be licensed where the patient lives, and a visit cannot be booked for a patient with no address. The address is saved only on a new Nurish'd account. An existing account is never changed. `state` is the province. `state` and `country` are two capital letters. ```bash curl -X POST https://api.dev.nurishd.ca/care/v1/patient/create/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "external_id": "patient-1001", "email": "ada.lovelace@example.com", "first_name": "Ada", "last_name": "Lovelace", "date_of_birth": "1990-12-10", "address": { "line1": "1 Example Street", "city": "Vancouver", "state": "BC", "postal_code": "V6B 1A1", "country": "CA" }, "return_url": "https://clinic.example.com/nurishd/return" }' ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/care/v1/patient/create/document', { method: 'POST', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ external_id: 'patient-1001', email: 'ada.lovelace@example.com', first_name: 'Ada', last_name: 'Lovelace', date_of_birth: '1990-12-10', address: { line1: '1 Example Street', city: 'Vancouver', state: 'BC', postal_code: 'V6B 1A1', country: 'CA', }, return_url: 'https://clinic.example.com/nurishd/return', }), }, ); const patient = await res.json(); ``` ```python import os import requests res = requests.post( "https://api.dev.nurishd.ca/care/v1/patient/create/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, json={ "external_id": "patient-1001", "email": "ada.lovelace@example.com", "first_name": "Ada", "last_name": "Lovelace", "date_of_birth": "1990-12-10", "address": { "line1": "1 Example Street", "city": "Vancouver", "state": "BC", "postal_code": "V6B 1A1", "country": "CA", }, "return_url": "https://clinic.example.com/nurishd/return", }, ) patient = res.json() ``` The answer: ```json { "user": "6f1c0d2e-0000-4000-8000-000000000101", "connection": { "connection_id": "connection-0001", "company_id": "company-0001", "user": "6f1c0d2e-0000-4000-8000-000000000101", "external_id": "patient-1001", "status": "pending", "scopes": ["care.bookings", "care.reports"], "created_at": "2026-11-30T15:04:05Z", "approved_at": null, "revoked_at": null, "revoked_by": null }, "connect_url": "https://app.nurishd.ca/connect/abc123", "connect_url_expires_at": "2026-12-01T15:04:05Z" } ``` The patient is asked to allow every care permission your key can use: `care.bookings` when it holds `booking:write`, `care.reports` when it holds `report:read`, and `care.health-profile` when it holds `health-profile:read` or `health-profile:write`. A key with none of those is refused with `403 scope_not_granted`. Only the scopes your key may ask for are listed in `scopes`. The patient's id is `user`. Use it as `patient_id` in the patient routes and as `user` when you book. The connection's id is `connection.connection_id`. Calling create again with the same `external_id` returns the same patient and a fresh link. The answer never says whether the email already had a Nurish'd account, and it never repeats the patient's name, email, date of birth or address. A patient is known to your company under one `external_id`. Two requests are refused with `409` and create nothing: | Code | When | | -------------------------- | ---------------------------------------------------------------------- | | `external_id_conflict` | The `external_id` already belongs to a patient with a different email. | | `person_already_connected` | The email is already connected under a different `external_id`. | To change the id you use for a patient, keep using the first one. ## What the patient does Send the patient to `connect_url` as a full page or a new tab. Never open it in a frame or a web view. The link is valid for 24 hours and works once. On the Nurish'd page the patient: 1. Enters a code sent to the email on their Nurish'd account, never to an address you supply. 2. Signs the health privacy agreement and the telehealth consent, if they are not signed yet. 3. Approves or declines. If the email had no account, Nurish'd creates one. If it had one, Nurish'd reuses it and changes nothing on it. In the Sandbox, no email is sent. The connect page accepts the fixed code `424242`. See [Environments](/docs/get-started/environments). ## Follow the connection > **Warning.** Never trust the `status` in the return URL. Anyone can edit a URL. The return URL carries `connection_id` and `status`. Use it only to know which connection to look at. Then do one of these: - Wait for the `connection.approved` event, or `connection.declined` if the patient declined. See [Events](/docs/events/events). - Read the connection with `GET /care/v1/connection/{connection_id}/get/document`: ```bash curl https://api.dev.nurishd.ca/care/v1/connection/connection-0001/get/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/care/v1/connection/connection-0001/get/document', { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const connection = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/care/v1/connection/connection-0001/get/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) connection = res.json() ``` ```json { "connection_id": "connection-0001", "company_id": "company-0001", "user": "6f1c0d2e-0000-4000-8000-000000000101", "external_id": "patient-1001", "status": "active", "scopes": ["care.bookings", "care.reports"], "created_at": "2026-11-30T15:04:05Z", "approved_at": "2026-11-30T15:10:12Z", "revoked_at": null, "revoked_by": null } ``` The status is brought up to date when you read it. A connection that does not exist, is not a care connection, or belongs to another company or environment answers `404 not_found`. | Status | Meaning | | ---------- | -------------------------------------------------------------------------------------------------- | | `pending` | The patient has not decided. Nothing can be booked. | | `active` | The patient approved. You can book. | | `declined` | The patient declined. Create again for a fresh link. | | `revoked` | The connection ended. `revoked_at` says when, and `revoked_by` is `patient`, `partner` or `admin`. | `GET /care/v1/patient/{patient_id}/get/document` returns the patient and the connection, with the status brought up to date. Its `connect_url` and `connect_url_expires_at` are always `null`. Call create again for a fresh link. ## Revoke the connection `PUT /care/v1/connection/{connection_id}/revoke/document` ends the connection. It raises a `connection.revoked` event. A connection that is already revoked or declined answers `409 connection_not_active`. ```bash curl -X PUT https://api.dev.nurishd.ca/care/v1/connection/connection-0001/revoke/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/care/v1/connection/connection-0001/revoke/document', { method: 'PUT', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const connection = await res.json(); ``` ```python import os import requests res = requests.put( "https://api.dev.nurishd.ca/care/v1/connection/connection-0001/revoke/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) connection = res.json() ``` The answer is the connection with `status` set to `revoked`, `revoked_at` set and `revoked_by` set to `partner`. Visits already booked stay booked, but you can no longer read or change them with your key. The patient and Nurish'd can revoke too. To connect again, call create with the same `external_id` and send the patient to the new `connect_url`. ## Next - [Connections](/docs/concepts/connections): statuses, scopes and return URLs. - [Saving a card](/docs/care/saving-a-card): the next step. A card must be on file before a visit can be booked. - [Booking a visit](/docs/care/booking-a-visit): book once a card is saved. - [BAA handling](/docs/care/baa): what care needs. --- # Saving a card Save a card to a connected patient's Nurish'd account with Stripe.js, so a visit can be booked for them. You will save a card to a patient's Nurish'd account, confirm it with Stripe.js on your own page, and list the saved cards. ## Why a card comes first A visit charges nothing when it is booked. The visit, a late-cancellation fee and a no-show fee are charged later to the patient's default saved card. A patient made through a company has no card. So a patient with no default card cannot be booked: booking answers `409 payment_method_required` and books nothing. The order of calls is: 1. Connect the patient. See [Connecting a patient](/docs/care/connecting-a-patient). 2. Save a card. This page. 3. Book. See [Booking a visit](/docs/care/booking-a-visit). Every route on this page needs the `patient:write` scope, an `active` connection and a connection that allows `care.bookings`. `patient:write` needs a signed BAA. See [BAA handling](/docs/care/baa). > **Warning.** The card is saved to the patient's Nurish'd account and may be charged for visits, late-cancellation fees and no-show fees. Tell the patient so before they type the card in. Nurish'd Connect keeps no record of card numbers. The patient types the card into Stripe's own form on your page. The number never reaches your server or Nurish'd's. ## Step 1: start the setup `POST /care/v1/patient/{patient_id}/payment-method/setup/create/document` starts saving a card. It takes no body. `patient_id` is the id from the create-patient answer. ```bash curl -X POST https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/payment-method/setup/create/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const patientId = '6f1c0d2e-0000-4000-8000-000000000101'; const res = await fetch( `https://api.dev.nurishd.ca/care/v1/patient/${patientId}/payment-method/setup/create/document`, { method: 'POST', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const setup = await res.json(); ``` ```python import os import requests patient_id = "6f1c0d2e-0000-4000-8000-000000000101" res = requests.post( f"https://api.dev.nurishd.ca/care/v1/patient/{patient_id}/payment-method/setup/create/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) setup = res.json() ``` ```json { "id": "seti_example", "client_secret": "seti_example_secret_example", "status": "requires_payment_method", "stripe_publishable_key": "pk_test_example" } ``` | Field | Meaning | | ------------------------ | ----------------------------------------------------------------------------------------- | | `id` | The id of the setup. You send it to the confirm route in step 3. | | `client_secret` | The secret the card form confirms the card with. Give it to Stripe.js only. Never log it. | | `status` | Where the setup is. It is `requires_payment_method` until a card is typed in. | | `stripe_publishable_key` | The Stripe publishable key to load Stripe.js with. `null` when none is configured. | Calling start again returns the same open setup while it is less than a day old. `stripe_publishable_key` can be `null` in an environment where Stripe is not configured yet. Your page cannot load Stripe.js then. Show an error and try again later. ## Step 2: confirm the card in the browser Send `stripe_publishable_key` and `client_secret` to your page. Never send your API key. The code below runs in the browser, on your company's page, not on your server. It uses [Stripe.js](https://docs.stripe.com/js) and a card element that you mounted. ```javascript // Runs in the browser, on your page. Not server code. const stripe = Stripe(publishableKey); const { error, setupIntent } = await stripe.confirmCardSetup(clientSecret, { payment_method: { card: cardElement }, }); if (error) { // Show error.message to the patient. Do not call the confirm route. } else { // The card form accepted the card. Tell your server to run step 3. } ``` `confirmCardSetup` is the Stripe.js call for a setup secret like the one the answer carries, which starts with `seti_`. When Stripe.js reports success, call the confirm route right away. It does not wait for any notification. ## Step 3: record the card `PUT /care/v1/patient/{patient_id}/payment-method/setup/{setup_id}/confirm/document` checks the setup and records the card on the patient's account. It takes no body. `setup_id` is the `id` from step 1. ```bash curl -X PUT https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/payment-method/setup/seti_example/confirm/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( `https://api.dev.nurishd.ca/care/v1/patient/${patientId}/payment-method/setup/${setup.id}/confirm/document`, { method: 'PUT', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const card = await res.json(); ``` ```python setup_id = setup["id"] res = requests.put( f"https://api.dev.nurishd.ca/care/v1/patient/{patient_id}/payment-method/setup/{setup_id}/confirm/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) card = res.json() ``` ```json { "id": "pm_example", "card": { "brand": "visa", "last4": "4242", "exp_month": 12, "exp_year": 2030 }, "is_default": true } ``` Calling confirm again for the same setup is safe. ### Which card is the default When the patient had no default card, the saved card becomes the default, and the answer says `is_default: true`. A patient who already has a default card keeps it, and the answer says `is_default: false`. Visits and fees are charged to the default card. ## List saved cards `GET /care/v1/patient/{patient_id}/payment-method/query/documents` returns the cards saved to the patient's account, at most 10, in one page. A patient with no card gets an empty `data` list. Each card has `id`, `card` (`brand`, `exp_month`, `exp_year` and `last4`) and `is_default`, which is `true` for the card visits and fees are charged to. ```bash curl https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/payment-method/query/documents \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( `https://api.dev.nurishd.ca/care/v1/patient/${patientId}/payment-method/query/documents`, { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY } }, ); const cards = await res.json(); ``` ```python res = requests.get( f"https://api.dev.nurishd.ca/care/v1/patient/{patient_id}/payment-method/query/documents", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) cards = res.json() ``` ```json { "data": [ { "id": "pm_example", "card": { "brand": "visa", "last4": "4242", "exp_month": 12, "exp_year": 2030 }, "is_default": true } ], "total": 1, "total_pages": 1, "page": 1, "size": 10, "has_next": false, "has_previous": false } ``` The patient can also add, remove and choose cards in their own Nurish'd account, so the list can change without you. Read it before you book if you need to know. ## Errors See [Errors](/docs/concepts/errors) for the shape. All three routes share the connection errors. | Status and code | What it means for you | | ------------------------------------- | --------------------------------------------------------------------------------------------------- | | `404 not_found` | The patient has no care connection with your company, or the setup is not this patient's. | | `403 connection_scope_not_granted` | The patient did not allow bookings. Create the patient again with a key that holds `booking:write`. | | `403 scope_not_granted` | The key lacks `patient:write`. See [Scopes](/docs/concepts/scopes). | | `409 connection_not_active` | The connection is `pending` or was revoked. Read the connection and wait for approval. | | `409 payment_method_setup_incomplete` | Confirm only: the card form has not confirmed the card yet. Finish step 2, then call confirm again. | ## What the Sandbox does > **Note.** Use Stripe test cards with a Sandbox key. Patients in the Sandbox are fake. See [Environments](/docs/get-started/environments). ## Next - [Booking a visit](/docs/care/booking-a-visit): book once a card is saved. - [Connecting a patient](/docs/care/connecting-a-patient): the step before this one. - [Scopes](/docs/concepts/scopes): what `patient:write` allows. --- # Booking a visit List specialists and services, read open times, then book, read and cancel visits for a connected patient. You will find a specialist and a service, pick an open time, book it for a connected patient, and read or cancel the visit later. Listing specialists, services and open times needs no patient and no BAA. Booking needs a patient whose connection is `active` and allows `care.bookings`. See [Connecting a patient](/docs/care/connecting-a-patient). A visit charges nothing when it is booked. It, a late-cancellation fee and a no-show fee are charged later to the patient's default saved card. So a card must be on file first. The order of calls is: connect the patient, save a card, book. See [Saving a card](/docs/care/saving-a-card). Without a card, booking answers `409 payment_method_required` and books nothing. ## List specialists `GET /care/v1/specialist/query/documents` returns a page of the specialists you can book, by name. All filters are optional. | Parameter | Meaning | | ---------------- | ------------------------------------------------------------------------------------------------------------ | | `type` | `Dietitian`, `Certified Nutrition Specialist` or `Physical Trainer`. | | `language` | A language the specialist speaks, such as `Spanish`. | | `specialization` | A specialization, such as `Weight Loss/Management`. | | `state` | Two capital letters, such as `ON`. The `specialist_locations` of each specialist then show only the matches. | | `name` | The start of the name, not case sensitive. One word matches the last name. | | `page`, `size` | See [Pagination](/docs/concepts/pagination). `size` is at most 50. | ```bash curl "https://api.dev.nurishd.ca/care/v1/specialist/query/documents?type=Dietitian&state=ON" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```json { "data": [ { "specialist_id": "3b7d9a52-0000-4000-8000-0000000000a1", "specialist_type": "Dietitian", "specialist_first_name": "Maya", "specialist_last_name": "Okafor", "specialist_locations": ["ON:CA"], "specialist_specializations": ["Weight Loss/Management"], "specialist_languages": [ { "language": "Spanish", "proficiency": "Native" } ] } ], "total": 1, "total_pages": 1, "page": 1, "size": 10, "has_next": false, "has_previous": false } ``` `specialist_locations` are places as `STATE:COUNTRY`. The list leaves out `specialist_long_introduction`. Read one specialist with `GET /care/v1/specialist/{specialist_id}/get/document` to get it. A specialist that does not exist, is not live, is hidden or was retired answers `404 not_found`. ## List a specialist's services `GET /care/v1/specialist/{specialist_id}/service/query/documents` takes `page` and `size`. ```bash curl https://api.dev.nurishd.ca/care/v1/specialist/3b7d9a52-0000-4000-8000-0000000000a1/service/query/documents \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` Each item in `data` looks like this. `service_price_in_cents` is in cents. `service_mode_of_delivery` is `Virtual` or `In Person`. ```json { "service_id": "service-initial-consult", "specialist": "3b7d9a52-0000-4000-8000-0000000000a1", "service_name": "Initial consult", "service_price_in_cents": 15000, "service_currency": "CAD", "service_duration_in_minutes": 60, "service_mode_of_delivery": "Virtual", "is_insurance_accepted": false } ``` Insurance cannot be used for a booking made through this API, whatever `is_insurance_accepted` says. ## Read open times `GET /care/v1/specialist/{specialist_id}/service/{service_id}/availability/query/documents` returns the times a patient can still book, earliest first, in UTC. Both `from` and `to` are required and carry a UTC offset. - The range must start before it ends and be at most 31 days long. Otherwise the answer is `422 invalid_time_range`. - A `from` in the past is moved up to the present. The answer says the range that was searched. - A service that cannot be booked online, such as one delivered in person, answers `409 service_not_bookable`. ```bash curl "https://api.dev.nurishd.ca/care/v1/specialist/3b7d9a52-0000-4000-8000-0000000000a1/service/service-initial-consult/availability/query/documents?from=2026-06-01T00:00:00Z&to=2026-06-08T00:00:00Z" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```json { "specialist_id": "3b7d9a52-0000-4000-8000-0000000000a1", "service_id": "service-initial-consult", "duration_in_minutes": 60, "start_time": "2026-06-01T00:00:00Z", "end_time": "2026-06-08T00:00:00Z", "slots": [ { "start_time": "2026-06-02T14:00:00Z", "end_time": "2026-06-02T15:00:00Z" }, { "start_time": "2026-06-02T15:00:00Z", "end_time": "2026-06-02T16:00:00Z" } ] } ``` The top-level `start_time` and `end_time` are the range that was searched. Pass the `start_time` of one slot as the `start_time` of a booking. ## Book a visit `POST /care/v1/booking/create/document` books one open time for a patient. | Field | Required | Notes | | --------------- | -------- | ------------------------------------------------------------------------------------------------------------------- | | `user` | Yes | The patient id from [Connecting a patient](/docs/care/connecting-a-patient). | | `specialist_id` | Yes | The specialist id. | | `service_id` | Yes | The service id. | | `start_time` | Yes | The `start_time` of an open time, with a UTC offset. | | `timezone` | Yes | The patient's IANA timezone, such as `America/Toronto`. | | `client_note` | No | A note for the specialist, at most 2000 characters. No `$`, `{` or `}`: one of them answers `422 validation_error`. | ```bash curl -X POST https://api.dev.nurishd.ca/care/v1/booking/create/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "user": "6f1c0d2e-0000-4000-8000-000000000101", "specialist_id": "3b7d9a52-0000-4000-8000-0000000000a1", "service_id": "service-initial-consult", "start_time": "2026-06-02T14:00:00Z", "timezone": "America/Toronto", "client_note": "I would like to talk about meal planning for the week." }' ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/care/v1/booking/create/document', { method: 'POST', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ user: '6f1c0d2e-0000-4000-8000-000000000101', specialist_id: '3b7d9a52-0000-4000-8000-0000000000a1', service_id: 'service-initial-consult', start_time: '2026-06-02T14:00:00Z', timezone: 'America/Toronto', client_note: 'I would like to talk about meal planning for the week.', }), }, ); const booking = await res.json(); ``` ```python import os import requests res = requests.post( "https://api.dev.nurishd.ca/care/v1/booking/create/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, json={ "user": "6f1c0d2e-0000-4000-8000-000000000101", "specialist_id": "3b7d9a52-0000-4000-8000-0000000000a1", "service_id": "service-initial-consult", "start_time": "2026-06-02T14:00:00Z", "timezone": "America/Toronto", "client_note": "I would like to talk about meal planning for the week.", }, ) booking = res.json() ``` ```json { "booking_id": "booking-0001", "booking_name": "Initial consult with Maya Okafor", "user": "6f1c0d2e-0000-4000-8000-000000000101", "specialist": "3b7d9a52-0000-4000-8000-0000000000a1", "specialist_snapshot": { "specialist_id": "3b7d9a52-0000-4000-8000-0000000000a1", "first_name": "Maya", "last_name": "Okafor", "specialist_type": "Dietitian" }, "service_snapshot": { "service_id": "service-initial-consult", "service_name": "Initial consult", "service_price_in_cents": 15000, "service_currency": "CAD", "service_duration_in_minutes": 60, "service_mode_of_delivery": "Virtual", "is_insurance_accepted": false }, "start_date": "2026-06-02T14:00:00Z", "end_date": "2026-06-02T15:00:00Z", "timezone": "America/Toronto", "status": "booked", "client_note": "I would like to talk about meal planning for the week.", "is_insurance_selected": false, "has_report": false, "created_at": "2026-05-20T15:04:05Z", "updated_at": "2026-05-20T15:04:05Z" } ``` If the patient has no default card, this answers `409 payment_method_required` and books nothing. Save a card first with [Saving a card](/docs/care/saving-a-card), then book again. `specialist_snapshot` and `service_snapshot` hold the specialist and the service as they were when the visit was booked. The `specialist` field is the specialist id. `is_insurance_selected` is always `false`. Booking the same patient, specialist and start again returns the first booking, so a retry after a timeout is safe. A new booking raises one `booking.created` event. A repeat raises none. ## Errors a booking can raise See [Errors](/docs/concepts/errors) for the shape. Do not retry a `409` unchanged. | Status and code | What it means for you | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `404 not_found` | The patient has no care connection with your company. | | `403 connection_scope_not_granted` | The patient did not allow bookings. Create the patient again with a key that holds `booking:write`, and send a new link. | | `409 connection_not_active` | The connection is `pending` or was revoked. Read the connection and wait for approval, or connect again. | | `409 payment_method_required` | The patient has no card saved. Nothing is booked. Save a card with [Saving a card](/docs/care/saving-a-card), then book again. | | `409 agreements_not_signed` | The patient has not signed the agreements a visit needs. Send them to a fresh `connect_url`. | | `409 service_not_bookable` | The service cannot be booked online, or the specialist or the service does not exist. Offer another service. | | `409 not_licensed_here` | The specialist cannot serve this booking yet. Offer another specialist. Check that the patient has an address. | | `409 slot_taken` | The time is no longer open. Read the open times again and offer another. | | `422 invalid_time_range` | On open times only: the range is empty, backwards or longer than 31 days. | ## List and read bookings `GET /care/v1/booking/query/documents` returns the visits your company booked, newest visit first. It leaves out visits the patient booked themselves, visits booked by another company, and visits of patients whose connection is no longer active. The list has no `client_note`: it reads as `null` there. | Parameter | Meaning | | -------------- | --------------------------------------------------------------------------------------- | | `patient` | Keep only the visits of this patient. | | `status` | `booked`, `meeting_rescheduled`, `meeting_completed`, `meeting_cancelled` or `no_show`. | | `from`, `to` | Keep visits that start at or after, or at or before, this time. UTC offset. | | `page`, `size` | See [Pagination](/docs/concepts/pagination). | The `status` filter works on the status last seen for each booking, and a booking is refreshed when you read it. A visit that changed outside this API can show under its old status until you read it. The status of each booking in the answer is current. ```bash curl "https://api.dev.nurishd.ca/care/v1/booking/query/documents?patient=6f1c0d2e-0000-4000-8000-000000000101&status=booked" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` `GET /care/v1/booking/{booking_id}/get/document` returns one booking with its `client_note`. A visit the patient or another company booked answers `404`. If the patient's connection was revoked, it answers `409 connection_not_active`: the visit stays booked, but you can no longer read or change it. If the patient or the specialist canceled, the answer says so and a `booking.canceled` event is raised once. ## Cancel a booking > **Warning.** A visit canceled less than 24 hours before it starts may be charged Nurish'd's late-cancellation fee, billed to the patient. Tell the patient before you cancel. `PUT /care/v1/booking/{booking_id}/cancel/document` cancels a visit your company booked. The body is optional. `reason` is at most 1000 characters. ```bash curl -X PUT https://api.dev.nurishd.ca/care/v1/booking/booking-0001/cancel/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" \ -H "Content-Type: application/json" \ -d '{"reason": "The patient asked to cancel."}' ``` The answer is the booking with `status` set to `meeting_cancelled`. A cancellation raises one `booking.canceled` event. A booking that is already canceled, completed or past answers `409 booking_not_cancelable`. A revoked connection answers `409 connection_not_active`. ## What the Sandbox simulates Open times are generated on weekdays from 9 to 5. They are not real calendars, no video link works, no email is delivered and patients are fake. See [Environments](/docs/get-started/environments). ## Next - [Connecting a patient](/docs/care/connecting-a-patient): connect before you book. - [Saving a card](/docs/care/saving-a-card): save a card before you book. - [Events](/docs/events/events): `booking.created` and `booking.canceled`. --- # Visit reports Learn when a dietitian signs a visit report, list your reports, read one with its sections and fetch the file of a section. You will learn when a dietitian signs the report of a visit you booked, list your reports, read one with its sections, and download the file of a section. All report routes need the `report:read` scope, which needs a signed BAA. See [BAA handling](/docs/care/baa). The patient must have an `active` connection that allows `care.reports`. See [Connecting a patient](/docs/care/connecting-a-patient). ## What you can see You get a report as the patient sees it. - Only signed reports. A report that is not signed yet is not visible to you. - Only reports of visits your company booked. A report of a visit the patient booked themselves, or that another company booked, is never listed and answers `404 not_found`. - Only the sections the specialist shared with the patient. Private notes and the patient's own details are never part of it. ## The report.signed event When a dietitian signs the report of a visit your company booked, one `report.signed` event is raised. The event is thin: it holds ids, never the report. ```json { "id": "evt_01JD2ZQ4M8K7R5T3V9X1B6C0HN", "type": "report.signed", "created": "2026-11-30T15:04:05Z", "mode": "prod", "data": { "object": "report", "id": "report-0001", "booking": "booking-0001", "patient": "patient-0001" } } ``` `data.id` is the report id. Fetch the report with your key. A key sees the event only when it holds `report:read`. See [Events](/docs/events/events) and [Webhooks](/docs/events/webhooks). ## List reports `GET /care/v1/report/query/documents` returns a page of signed reports, newest signed first. All filters are optional. | Parameter | Meaning | | -------------- | ------------------------------------------------------------------------ | | `patient` | Keep only the reports of this patient. | | `booking` | Keep only the reports of this booking. | | `from`, `to` | Keep reports signed at or after, or at or before, this time. UTC offset. | | `page`, `size` | See [Pagination](/docs/concepts/pagination). `size` is at most 50. | ```bash curl "https://api.dev.nurishd.ca/care/v1/report/query/documents?booking=booking-0001" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const params = new URLSearchParams({ booking: 'booking-0001' }); const res = await fetch( `https://api.dev.nurishd.ca/care/v1/report/query/documents?${params}`, { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY } }, ); const reports = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/care/v1/report/query/documents", params={"booking": "booking-0001"}, headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) reports = res.json() ``` The list is thin: it holds only ids and `signed_at`. `user` is the patient and `specialist` is the specialist id. Read one report to get its sections. ```json { "data": [ { "report_id": "report-0001", "booking_id": "booking-0001", "user": "patient-0001", "specialist": "3b7d9a52-0000-4000-8000-0000000000a1", "signed_at": "2026-11-30T15:04:05Z" } ], "total_pages": 1, "total": 1, "page": 1, "size": 10, "has_next": false, "has_previous": false } ``` If you ask for one `booking` and no report of it is known yet, the call also looks for a signed report of that visit. A report whose event you missed still shows up, and its event is raised once. A patient whose connection is no longer active is left out of the list. ## Read one report `GET /care/v1/report/{report_id}/get/document` returns the report and its shared sections, lowest `section_order` first. ```bash curl https://api.dev.nurishd.ca/care/v1/report/report-0001/get/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/care/v1/report/report-0001/get/document', { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY } }, ); const report = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/care/v1/report/report-0001/get/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) report = res.json() ``` ```json { "report_id": "report-0001", "booking_id": "booking-0001", "user": "patient-0001", "specialist": "3b7d9a52-0000-4000-8000-0000000000a1", "specialist_snapshot": { "specialist_id": "3b7d9a52-0000-4000-8000-0000000000a1", "first_name": "Maya", "last_name": "Okafor", "full_name": "Maya Okafor", "specialist_type": "Dietitian" }, "status": "signed", "signed_at": "2026-11-30T15:04:05Z", "created_at": "2026-11-30T14:10:00Z", "updated_at": "2026-11-30T15:04:05Z", "sections": [ { "section_id": "section-0001", "report_id": "report-0001", "section_name": "Summary", "section_type": "note", "section_description": null, "section_order": 1, "section_content": "You are on track. Keep the plan for two weeks.", "has_file": false, "signed_on": "2026-11-30T15:04:05Z", "created_at": "2026-11-30T14:10:00Z", "updated_at": "2026-11-30T15:04:05Z" }, { "section_id": "section-0002", "report_id": "report-0001", "section_name": "Lab results", "section_type": "pdf", "section_description": null, "section_order": 2, "section_content": null, "has_file": true, "signed_on": null, "created_at": "2026-11-30T14:10:00Z", "updated_at": "2026-11-30T14:10:00Z" } ] } ``` | Field | Meaning | | --------------------------------------------- | ----------------------------------------------------------------------------- | | `status` | `draft` or `signed`. You see signed reports. | | `sections[].section_type` | `note`, `table`, `image`, `pdf` or `signature`. | | `sections[].section_content` | The Markdown body. An `image` or a `pdf` section has none: read its file. | | `sections[].section_order` | The render order of the section, lowest first. | | `sections[].has_file` | `true` for a section with a file to download. | | `specialist_snapshot.first_name`, `last_name` | The name as it stood when the report was written. `full_name` is for display. | ## Fetch the file of a section For a section with `has_file: true`, call `GET /care/v1/report/{report_id}/section/{section_id}/file/get/document`. It answers a link. ```bash curl https://api.dev.nurishd.ca/care/v1/report/report-0001/section/section-0002/file/get/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/care/v1/report/report-0001/section/section-0002/file/get/document', { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY } }, ); const { url } = await res.json(); const file = await fetch(url); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/care/v1/report/report-0001/section/section-0002/file/get/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) file = requests.get(res.json()["url"]) ``` ```json { "url": "https://files.example.com/signed-link" } ``` > **Warning.** The link works for a short time only. Download the file at once. Do not store the link or log it. Call the route again when you need the file again. A section the specialist did not share, or a section without a file, answers `404 not_found`. ## After a connection is revoked When the patient revokes the connection, your access ends at once, even for a report you were told about. - The list no longer shows that patient. - Reading a report or a file answers `409 connection_not_active`. ## Errors See [Errors](/docs/concepts/errors) for the shape. Do not retry a `4xx` unchanged. | Status and code | What it means for you | | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `403 scope_not_granted` | The key lacks `report:read`. | | `403 connection_scope_not_granted` | The patient does not share reports. Connect again and ask for `care.reports`. | | `404 not_found` | The report does not exist, or the visit was booked by the patient or another company. Also a section not shared, or one without a file. | | `409 connection_not_active` | The connection was revoked. You can no longer read this patient's reports. | | `422 validation_error` | A parameter is invalid, such as a `size` over 50. | ## What the Sandbox simulates In the Sandbox a visit does not finish by itself, so no report appears. The test helper marks a visit done and signs a sample report. It needs the `booking:write` scope and works with Sandbox keys only: a Production key gets `403 test_mode_only`. `POST /developer/v1/test-helper/booking/{booking_id}/complete/document` takes no body. The booking must be one your company made with a Sandbox key, otherwise the answer is `404`. A booking that was canceled or is already completed answers `409 booking_not_completable`. ```bash curl -X POST https://api.dev.nurishd.ca/developer/v1/test-helper/booking/booking-0001/complete/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```json { "booking_id": "booking-0001", "report_id": "report-0001", "status": "meeting_completed" } ``` The visit is now `meeting_completed` and the sample report is signed. Its content is invented. The `report.signed` event follows shortly after the route answers, and the report routes above work for `report_id`. ## Next - [Booking a visit](/docs/care/booking-a-visit): book first. - [Events](/docs/events/events): poll or receive events. - [BAA handling](/docs/care/baa): what the report scope needs. --- # Health profiles Read a connected patient's health profile and replace it, with the measurement rules and the errors. You will read the health profile of a connected patient, replace it with an update, and handle the measurement rules. ## What you need - A signed BAA on your company. `health-profile:read` and `health-profile:write` both need it. See [BAA handling](/docs/care/baa). - A patient whose connection is `active` and carries `care.health-profile`. The patient approves it on the connect page. - A patient who did not approve that scope makes calls answer `403 connection_scope_not_granted`. Asking for the scope on an existing connection puts it back to `pending` until the patient approves again. ## Read a profile `GET /care/v1/patient/{patient_id}/health-profile/get/document` returns the profile with the latest measurement. `patient_id` is the id that creating the patient answered. ```bash curl https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/get/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/get/document', { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY } }, ); const profile = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/get/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) profile = res.json() ``` ```json { "user": "6f1c0d2e-0000-4000-8000-000000000101", "biological_sex": "Female", "date_of_birth": "1990-12-10", "medications": [ { "medication_name": "Metformin", "dosage_amount": 500, "dosage_unit": "mg", "frequency": "Twice daily" } ], "supplements": [], "has_diabetes": true, "diabetes_information": { "diabetes_type": "Type 2", "does_user_have_family_history_of_diabetes": true, "does_user_have_diabetic_complications": false }, "has_heart_condition": false, "heart_condition_information": null, "has_other_diseases": false, "other_diseases_notes": null, "additional_information": "Prefers vegetarian meals.", "general_health_data": { "height_in_cm": 165.5, "weight_in_kg": 70.25, "activity_level": "Moderate", "goal": "Managed Condition", "managed_condition": "Diabetes [Weight Loss]", "date_of_measurement": "2026-11-30T15:04:05Z" }, "created_at": "2026-11-30T15:04:05Z", "updated_at": "2026-11-30T15:04:05Z" } ``` `has_diabetes`, `has_heart_condition` and `has_other_diseases` say whether the patient has the condition. `diabetes_information` and `heart_condition_information` are `null` when none was saved. `other_diseases_notes` holds the other diseases. `general_health_data` is the latest measurement, and is `null` when there is none. A patient with no profile yet answers `404 health_profile_not_found`. Create it with the update route. ## Update a profile `PUT /care/v1/patient/{patient_id}/health-profile/update/document` saves the profile. It creates the profile the first time and replaces it every time after. The answer is the profile, as the read route gives it. > **Warning.** An update is a full replace, not a patch. Send every field you want to keep. A field you leave out is cleared. To change one thing, read the profile, change it and send all of it back. | Field | Required | Notes | | ----------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------- | | `biological_sex` | Yes | `Male`, `Female` or `Prefer not to say`. | | `date_of_birth` | Yes | `YYYY-MM-DD`. | | `medications`, `supplements` | No | At most 10 each, each with `medication_name`. Send an empty list when there are none. | | `has_diabetes`, `has_heart_condition`, `has_other_diseases` | No | Whether the patient has the condition. A flag you leave out is `false`. | | `diabetes_information`, `heart_condition_information`, `other_diseases_notes` | No | The details. Required when the flag is `true`. See below. | | `additional_information` | No | At most 1000 characters. | | `general_health_data` | No | A new measurement. Required on the first save. See below. | Each condition has a flag and a block of details. `has_diabetes: true` needs `diabetes_information`, `has_heart_condition: true` needs `heart_condition_information`, and `has_other_diseases: true` needs `other_diseases_notes` (at most 1000 characters). Otherwise the answer is `422 validation_error`. A block sent with its flag `false` is not refused and is saved as sent. Enum values are listed for each field in the [API reference](/reference). The first save needs a measurement: ```bash curl -X PUT https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/update/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "biological_sex": "Female", "date_of_birth": "1990-12-10", "medications": [{"medication_name": "Metformin", "dosage_amount": 500, "dosage_unit": "mg", "frequency": "Twice daily"}], "has_diabetes": true, "diabetes_information": { "diabetes_type": "Type 2", "does_user_have_family_history_of_diabetes": true, "does_user_have_diabetic_complications": false }, "additional_information": "Prefers vegetarian meals.", "general_health_data": { "height_in_cm": 165.5, "weight_in_kg": 70.25, "activity_level": "Moderate", "goal": "Managed Condition", "managed_condition": "Diabetes [Weight Loss]" } }' ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/update/document', { method: 'PUT', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ biological_sex: 'Female', date_of_birth: '1990-12-10', medications: [ { medication_name: 'Metformin', dosage_amount: 500, dosage_unit: 'mg', frequency: 'Twice daily', }, ], has_diabetes: true, diabetes_information: { diabetes_type: 'Type 2', does_user_have_family_history_of_diabetes: true, does_user_have_diabetic_complications: false, }, additional_information: 'Prefers vegetarian meals.', general_health_data: { height_in_cm: 165.5, weight_in_kg: 70.25, activity_level: 'Moderate', goal: 'Managed Condition', managed_condition: 'Diabetes [Weight Loss]', }, }), }, ); ``` ```python import os import requests res = requests.put( "https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/update/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, json={ "biological_sex": "Female", "date_of_birth": "1990-12-10", "medications": [ {"medication_name": "Metformin", "dosage_amount": 500, "dosage_unit": "mg", "frequency": "Twice daily"} ], "has_diabetes": True, "diabetes_information": { "diabetes_type": "Type 2", "does_user_have_family_history_of_diabetes": True, "does_user_have_diabetic_complications": False, }, "additional_information": "Prefers vegetarian meals.", "general_health_data": { "height_in_cm": 165.5, "weight_in_kg": 70.25, "activity_level": "Moderate", "goal": "Managed Condition", "managed_condition": "Diabetes [Weight Loss]", }, }, ) ``` ## Change one field: read, modify, write To change the notes and keep everything else, read the profile and send it back. Drop `user`, `created_at`, `updated_at` and `general_health_data` from what you read: they are not input fields. Leaving `general_health_data` out keeps the measurement history as it is. ```javascript const getUrl = 'https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/get/document'; const putUrl = 'https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/update/document'; const headers = { 'X-Partner-API-Key': process.env.NURISHD_API_KEY, 'Content-Type': 'application/json', }; const current = await (await fetch(getUrl, { headers })).json(); const { user, created_at, updated_at, general_health_data, ...profile } = current; const res = await fetch(putUrl, { method: 'PUT', headers, body: JSON.stringify({ ...profile, additional_information: 'Prefers vegetarian meals, no nuts.', }), }); ``` ```python import os import requests get_url = "https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/get/document" put_url = "https://api.dev.nurishd.ca/care/v1/patient/6f1c0d2e-0000-4000-8000-000000000101/health-profile/update/document" headers = {"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]} current = requests.get(get_url, headers=headers).json() profile = {k: v for k, v in current.items() if k not in ("user", "created_at", "updated_at", "general_health_data")} profile["additional_information"] = "Prefers vegetarian meals, no nuts." res = requests.put(put_url, headers=headers, json=profile) ``` ## Measurement rules `general_health_data` is a measurement. It adds one entry to the patient's history, and the read route answers the latest one, with `date_of_measurement`. It holds `height_in_cm`, `weight_in_kg`, `activity_level`, `goal`, `managed_condition` and the lifestyle fields `alcohol_consumption_frequency`, `sleep_quality`, `smoking_status` and `stress_level`. - The first save needs `general_health_data`. Without it the answer is `422 measurement_required`. - A patient can have one measurement every 24 hours. A `general_health_data` sent sooner answers `409 measurement_too_recent`, and nothing is saved, not even the rest of the profile. - To change the profile alone, leave `general_health_data` out. - `managed_condition` is required in `general_health_data` when `goal` is `Managed Condition`, and not allowed for any other goal. ## Errors See [Errors](/docs/concepts/errors) for the shape. Do not retry a `4xx` unchanged. | Status and code | What it means for you | | ---------------------------------- | ---------------------------------------------------------------------------------------------------- | | `403 scope_not_granted` | The key lacks `health-profile:read` or `health-profile:write`. | | `403 connection_scope_not_granted` | The patient did not approve `care.health-profile`. | | `404 not_found` | The patient does not exist, or belongs to another company or environment. | | `404 health_profile_not_found` | The patient has no profile yet. Create it with an update that has a measurement. | | `409 connection_not_active` | The connection is `pending` or was revoked. Read the connection. | | `409 measurement_too_recent` | The patient has a measurement from the last 24 hours. Send the update without `general_health_data`. | | `422 measurement_required` | A first save has no `general_health_data`. Add it. | | `422 validation_error` | A field is missing or invalid. Nothing was saved. | ## Handling the data A health profile is patient data. Do not log it, do not send it to support, and do not paste it into an AI prompt. See [Support](/docs/resources/support). ## Next - [Connecting a patient](/docs/care/connecting-a-patient): get a connection. - [BAA handling](/docs/care/baa): the rules. - [Scopes](/docs/concepts/scopes): all ten scopes. --- # BAA handling Which scopes need a business associate agreement and what a company without one can do. You will know which scopes need a BAA, what happens without one, and what to do to get access to patient data. A BAA is a business associate agreement between your company and Nurish'd. Nurish'd records its signing date on your company. You do not set it in the console. ## Which scopes need a BAA | Scope | Needs a BAA | | ---------------------- | ----------- | | `patient:write` | Yes | | `booking:read` | Yes | | `booking:write` | Yes | | `report:read` | Yes | | `health-profile:read` | Yes | | `health-profile:write` | Yes | | `specialist:read` | No | | `catalog:read` | No | | `order:read` | No | | `order:write` | No | Read does not remove the need for a BAA. A booking says that a person sees a dietitian at a given time. Reading it discloses health information exactly as writing it does. ## What a company without a BAA can do - List specialists, their services and open times with `specialist:read`. See [Booking a visit](/docs/care/booking-a-visit). - Use meals: the catalog, customers and orders. - Not create a patient, and not read or write anything about any patient. A call that needs a BAA scope answers `403 scope_not_granted`. ```json { "error": { "code": "scope_not_granted", "message": "This key does not hold the scope this route needs.", "request_id": "req-0001" } } ``` ## How the rule is enforced - Nurish'd cannot grant a BAA scope to a company with no BAA date. - Every call is checked again. If the BAA date is cleared, the care scopes disappear from the company and from every key within a minute. - A key narrowed to `booking:read` cannot book. It answers `403 scope_not_granted` on a booking create. ## What to do 1. Sign a BAA with Nurish'd. Ask your Nurish'd contact or email `hello@nurishd.io`. 2. Nurish'd records the BAA date and grants the care scopes to your company. 3. Owners and admins can then create keys that hold them. ## Handling patient data - Never send patient data to support, in a ticket, a chat or an AI prompt. - Do not log response bodies of care routes. Log ids and `request_id`. - Do not store the time-limited link to a report file. Download the file and drop the link. - Events never carry patient data. They carry ids. Fetch the object with your key. ## Next - [Scopes](/docs/concepts/scopes): all ten scopes. - [Company settings](/docs/console/company-settings): what Nurish'd controls. - [Connecting a patient](/docs/care/connecting-a-patient): the first care step. --- # Events The thin event object, the event types and their scopes, listing and filtering, and a polling pattern with a cursor. You will read what happened to your company's connections, bookings, reports and orders, and poll for new events without missing any. ## The event object An event says what happened and to which object. It never carries the object. Fetch the object with your key. ```json { "id": "evt_01JD2ZQ4M8K7R5T3V9X1B6C0HN", "type": "report.signed", "created": "2026-11-30T15:04:05Z", "mode": "prod", "data": { "object": "report", "id": "report-0001", "booking": "booking-0001", "patient": "patient-0001" } } ``` | Field | Meaning | | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `id` | The event id, starting with `evt_`. | | `type` | What happened. | | `created` | When, in UTC. | | `mode` | `test` for the Sandbox, `prod` for Production. | | `data.object` | The kind of object: `connection`, `booking`, `report`, `order` or `ping`. | | `data.id` | The id of that object. | | `data.patient`, `data.customer`, `data.connection`, `data.booking`, `data.report`, `data.order` | Related ids. Present only when they apply. Care events carry `patient`. Meals and order events carry `customer`. A connection event carries `customer` for a meals connection and `patient` for a care connection. | Events are thin so that no health data sits in webhook bodies, delivery logs or your request logs. Ignore fields you do not know. ## Event types | Type | When | Scope that lets a key see it | | --------------------- | -------------------------------------------- | ------------------------------------------- | | `connection.approved` | A customer or patient approved a connection. | See the note below. | | `connection.declined` | They declined. | See the note below. | | `connection.revoked` | The connection ended. | See the note below. | | `booking.created` | A visit was booked. | `booking:read` | | `booking.canceled` | A visit was canceled. | `booking:read` | | `report.signed` | A dietitian signed a visit report. | `report:read` | | `order.created` | An order was created. | `order:read` | | `order.paid` | An order was paid. | `order:read` | | `order.fulfilled` | An order was fulfilled. | `order:read` | | `order.shipped` | An order was shipped. | `order:read` | | `order.delivered` | An order was delivered. | `order:read` | | `order.refunded` | An order was refunded. | `order:read` | | `order.canceled` | An order was canceled. | `order:read` | | `ping` | A test event sent from the console. | No scope. Cannot be chosen for an endpoint. | A key sees only the types its scopes allow. A key without the scope for a type does not list it, and `GET /developer/v1/event/{event_id}/get/document` answers `404 not_found` for it. > **Note.** Which scope shows a connection event depends on the product the connection is for. Check what a key sees by listing events with it. `report.signed` is raised for visits your company booked. See [Visit reports](/docs/care/reports). An order event looks like this: ```json { "id": "evt_01JD2ZQ4M8K7R5T3V9X1B6C0HN", "type": "order.paid", "created": "2026-04-01T15:06:30Z", "mode": "test", "data": { "object": "order", "id": "ORD-ONE-OFF-4F7K2A9Q", "order": "ORD-ONE-OFF-4F7K2A9Q", "customer": "6f1c0d2e-0000-4000-8000-000000000101" } } ``` Every order event, from `order.created` to `order.canceled`, carries the order as `data.id` and the customer as `data.customer`. Booking events, `booking.created` and `booking.canceled`, are raised by the care routes in [Booking a visit](/docs/care/booking-a-visit). Order events are raised by the routes in [Orders](/docs/meals/orders). ## List events `GET /developer/v1/event/query/documents` returns events from the last 30 days, newest first, in the mode of your key. | Parameter | Meaning | | -------------- | ---------------------------------------------------------------------- | | `type` | Keep only this event type, such as `connection.approved`. | | `from` | Keep events created at or after this time. ISO 8601 with a time zone. | | `to` | Keep events created at or before this time. ISO 8601 with a time zone. | | `page`, `size` | See [Pagination](/docs/concepts/pagination). | ```bash curl "https://api.dev.nurishd.ca/developer/v1/event/query/documents?type=connection.approved&size=10" \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const params = new URLSearchParams({ type: 'connection.approved', size: '10' }); const res = await fetch( `https://api.dev.nurishd.ca/developer/v1/event/query/documents?${params}`, { headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const events = await res.json(); ``` ```python import os import requests res = requests.get( "https://api.dev.nurishd.ca/developer/v1/event/query/documents", params={"type": "connection.approved", "size": 10}, headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) events = res.json() ``` ```json { "data": [ { "id": "evt_01JD2ZQ4M8K7R5T3V9X1B6C0HN", "type": "connection.approved", "created": "2026-11-30T15:10:12Z", "mode": "test", "data": { "object": "connection", "id": "connection-0001", "connection": "connection-0001", "customer": "6f1c0d2e-0000-4000-8000-000000000101" } } ], "total_pages": 1, "total": 1, "page": 1, "size": 10, "has_next": false, "has_previous": false } ``` `GET /developer/v1/event/{event_id}/get/document` returns one event. ## Poll with a cursor Webhooks deliver events as they happen. Poll the list as a safety net, or if you have no endpoint yet. Keep the `created` time of the newest event you handled and ask only for events at or after it. 1. Call the list with `from` set to your cursor. 2. Walk the pages. Events come newest first. 3. Skip event ids you already handled. `from` is inclusive, so the newest event comes back again. 4. Handle the rest from oldest to newest. 5. Save the newest `created` as the new cursor, only after you handled everything. ```javascript const base = 'https://api.dev.nurishd.ca/developer/v1/event/query/documents'; const headers = { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }; async function poll(cursor, seen) { const fresh = []; for (let page = 1; ; page++) { const params = new URLSearchParams({ from: cursor, size: '50', page: String(page), }); const body = await ( await fetch(`${base}?${params}`, { headers }) ).json(); fresh.push(...body.data.filter((e) => !seen.has(e.id))); if (!body.has_next) break; } fresh.reverse(); for (const event of fresh) { await handle(event); seen.add(event.id); cursor = event.created; } return cursor; } ``` ```python import os import requests BASE = "https://api.dev.nurishd.ca/developer/v1/event/query/documents" HEADERS = {"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]} def poll(cursor, seen): fresh, page = [], 1 while True: body = requests.get( BASE, headers=HEADERS, params={"from": cursor, "size": 50, "page": page} ).json() fresh += [e for e in body["data"] if e["id"] not in seen] if not body["has_next"]: break page += 1 for event in reversed(fresh): handle(event) seen.add(event["id"]) cursor = event["created"] return cursor ``` Store the cursor and the handled ids in your database. Events are listed for 30 days, so a cursor older than that misses events. Poll at a pace your [rate limit](/docs/concepts/rate-limits) allows, such as once a minute. Make your handler safe to run twice for the same event. ## Next - [Webhooks](/docs/events/webhooks): receive events by HTTPS. - [Connections](/docs/concepts/connections): the connection events. - [Pagination](/docs/concepts/pagination): pages and filters. --- # Webhooks Register a webhook endpoint, choose its events, send a test event and understand retries. You will register an HTTPS endpoint, choose the events it receives, test it, and know what a delivery looks like. ## How it works A webhook endpoint is an HTTPS address. When an event of a type you chose happens, Nurish'd sends it to the endpoint as a `POST` with a JSON body. The body is the [event](/docs/events/events). Each delivery is signed with the endpoint's signing secret. - A company can have at most 10 endpoints per environment. The 11th answers `409 webhook_endpoint_limit_reached`. - An endpoint belongs to one environment. A Sandbox endpoint receives only Sandbox events. - Each endpoint has its own signing secret, `nk-whsec-` followed by 64 hex characters. ## What a delivery looks like - The method is `POST`. The body is the compact JSON of the public event shape, the same object the event list returns. See [Events](/docs/events/events). - The `Content-Type` is `application/json`. The `User-Agent` is `Nurishd-Connect-Webhooks/1.0`. - The `Nurishd-Signature` header signs the raw body: `t=,v1=.">`. During the 24 hours after you roll a secret it carries a second `v1=` value. Check it as shown in [Verifying signatures](/docs/events/verifying-signatures). - Events are thin. Fetch the object with your key. ## Create an endpoint Create one in the console under **Webhooks**, or with the API. The URL must be public: `https` only, no user name or password, no fragment, no `localhost` or private IP address. Choose at least one event type, each once. You cannot choose `ping`. Your key's scopes must let it see every type you choose, otherwise the call answers `403 scope_not_granted`. `POST /developer/v1/webhook-endpoint/create/document`: ```bash curl -X POST https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/create/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://hooks.example.com/nurishd", "events": ["connection.approved", "connection.revoked"], "description": "Connections for the back office" }' ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/create/document', { method: 'POST', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ url: 'https://hooks.example.com/nurishd', events: ['connection.approved', 'connection.revoked'], description: 'Connections for the back office', }), }, ); const created = await res.json(); ``` ```python import os import requests res = requests.post( "https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/create/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, json={ "url": "https://hooks.example.com/nurishd", "events": ["connection.approved", "connection.revoked"], "description": "Connections for the back office", }, ) created = res.json() ``` The answer is `201`. The signing secret is in `secret` and is shown here. You can read it again in the console. Store it like an API key. ```json { "endpoint": { "endpoint_id": "whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN", "company_id": "company-0001", "mode": "test", "url": "https://hooks.example.com/nurishd", "events": ["connection.approved", "connection.revoked"], "description": "Connections for the back office", "is_enabled": true, "secret_last_four": "e5f6", "previous_secret_expires_at": null, "created_at": "2026-11-30T15:04:05Z", "updated_at": "2026-11-30T15:04:05Z" }, "secret": "nk-whsec-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" } ``` ## List, change and delete | Route | What it does | | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | `GET /developer/v1/webhook-endpoint/query/documents` | List endpoints in your key's mode, newest first. The secret is not listed, only `secret_last_four`. | | `PUT /developer/v1/webhook-endpoint/{endpoint_id}/update/document` | Change `url`, `events`, `description` or `is_enabled`. Fields you leave out stay as they are. | | `PUT /developer/v1/webhook-endpoint/{endpoint_id}/secret/roll/document` | Make a new signing secret. See [Verifying signatures](/docs/events/verifying-signatures). | | `DELETE /developer/v1/webhook-endpoint/{endpoint_id}/delete/document` | Delete an endpoint. Events are no longer sent to it. | ## Pause and resume Send `is_enabled: false` to pause deliveries. Send `is_enabled: true` to start again. Sending `description: null` clears the description. `events` replaces the whole list. ```bash curl -X PUT https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN/update/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" \ -H "Content-Type: application/json" \ -d '{"is_enabled": false}' ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN/update/document', { method: 'PUT', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY, 'Content-Type': 'application/json', }, body: JSON.stringify({ is_enabled: false }), }, ); ``` ```python import os import requests res = requests.put( "https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN/update/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, json={"is_enabled": False}, ) ``` The answer is the endpoint, with the same fields as in the create answer and no `secret`. `previous_secret_expires_at` is set for 24 hours after you roll the secret and is `null` otherwise. An endpoint of the other environment answers `404 not_found`. ## Send a test event In the console, select **Send test event** on an endpoint. Nurish'd sends a signed `ping`. Use it to test your signature check before any real event. ## Retries Your endpoint has 5 seconds to answer. A `2xx` answer is success. Any other answer, a timeout or a connection error is a failure, and Nurish'd retries with backoff for up to three days. Nurish'd does not follow redirects, so a `301` or `302` counts as a failure: register the final URL. Answer fast with a `2xx` and do your work after. Make your handler safe to run twice for the same event id. Keep polling the event list as a safety net. See [Events](/docs/events/events). ## Next - [Verifying signatures](/docs/events/verifying-signatures): check every delivery. - [Events](/docs/events/events): the event object and types. - [Managing keys](/docs/console/managing-keys): who can manage endpoints. --- # Verifying signatures Verify the Nurishd-Signature header on every webhook delivery, with working Node, Python and PHP code, and roll a signing secret safely. You will verify that a webhook delivery came from Nurish'd and was not changed or replayed, and you will roll a signing secret without missing events. ## The header Every delivery carries one header. ```text Nurishd-Signature: t=1764515045,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd ``` - `t` is the Unix time in seconds when Nurish'd signed the delivery. - `v1` is the hex HMAC-SHA256 of the string `.`, using the endpoint's signing secret as the key. The body is the compact JSON of the event, exactly as sent. - After you roll a secret, the header carries two `v1=` values for 24 hours, one per secret: ```text Nurishd-Signature: t=1764515045,v1=,v1= ``` ## Steps 1. Read the raw request body as bytes or an exact string. Do not parse and re-serialize it. Any change to the bytes breaks the signature. 2. Read the `Nurishd-Signature` header. Split it on `,`, then each part on the first `=`. Take `t` and collect every `v1`. 3. Reject the delivery if `t` is more than five minutes old. The code below also rejects a `t` more than five minutes in the future. This stops replays. 4. Compute the HMAC-SHA256 of `t + "." + raw body` with your signing secret, as hex. 5. Compare it to each `v1` with a constant-time comparison. Accept if any one matches. 6. Only then parse the body as JSON. Answer with a failure status (`400`) when verification fails, and do not process the body. A `2xx` is success, anything else is retried, and redirects are not followed. See [Webhooks](/docs/events/webhooks). The request carries `User-Agent: Nurishd-Connect-Webhooks/1.0`. Do not trust a request by its User-Agent: only the signature proves who sent it. ## Node This uses only the standard library. With Express, read the raw body with `express.raw({ type: "application/json" })`. ```javascript import crypto from 'node:crypto'; const TOLERANCE_SECONDS = 300; /** * @param {Buffer | string} rawBody the exact bytes received * @param {string | undefined} header the Nurishd-Signature header * @param {string} secret the signing secret, starting with nk-whsec- * @returns {boolean} */ export function verifySignature(rawBody, header, secret) { if (!header) return false; let timestamp = null; const signatures = []; for (const part of header.split(',')) { const index = part.indexOf('='); if (index === -1) continue; const key = part.slice(0, index).trim(); const value = part.slice(index + 1).trim(); if (key === 't') timestamp = value; if (key === 'v1') signatures.push(value); } if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false; const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)); if (age > TOLERANCE_SECONDS) return false; const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, 'utf8'); const expected = crypto .createHmac('sha256', secret) .update(Buffer.concat([Buffer.from(`${timestamp}.`, 'utf8'), body])) .digest(); return signatures.some((signature) => { if (!/^[0-9a-f]{64}$/i.test(signature)) return false; const received = Buffer.from(signature, 'hex'); return ( received.length === expected.length && crypto.timingSafeEqual(received, expected) ); }); } ``` ```javascript import express from 'express'; import { verifySignature } from './verify-signature.js'; const app = express(); app.post('/nurishd', express.raw({ type: 'application/json' }), (req, res) => { const ok = verifySignature( req.body, req.get('Nurishd-Signature'), process.env.NURISHD_WEBHOOK_SECRET, ); if (!ok) return res.sendStatus(400); const event = JSON.parse(req.body.toString('utf8')); // Handle by event.id so a repeated delivery does no harm. res.sendStatus(200); }); ``` ## Python ```python import hashlib import hmac import time TOLERANCE_SECONDS = 300 def verify_signature(raw_body: bytes, header: str | None, secret: str) -> bool: """Return True if the delivery is genuine and fresh. raw_body is the exact bytes received. header is the Nurishd-Signature value. """ if not header: return False timestamp = None signatures = [] for part in header.split(","): key, sep, value = part.partition("=") if not sep: continue key, value = key.strip(), value.strip() if key == "t": timestamp = value elif key == "v1": signatures.append(value) if timestamp is None or not timestamp.isdigit() or not signatures: return False if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS: return False expected = hmac.new( secret.encode("utf-8"), timestamp.encode("utf-8") + b"." + raw_body, hashlib.sha256, ).hexdigest() return any(hmac.compare_digest(expected, signature.lower()) for signature in signatures) ``` With Flask, use `request.get_data()` for the raw body. ```python import os from flask import Flask, request app = Flask(__name__) @app.post("/nurishd") def nurishd(): ok = verify_signature( request.get_data(), request.headers.get("Nurishd-Signature"), os.environ["NURISHD_WEBHOOK_SECRET"], ) if not ok: return "", 400 event = request.get_json() # Handle by event["id"] so a repeated delivery does no harm. return "", 200 ``` ## PHP ```php TOLERANCE_SECONDS) { return false; } $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret); foreach ($signatures as $signature) { if (hash_equals($expected, strtolower($signature))) { return true; } } return false; } $rawBody = file_get_contents('php://input'); $header = $_SERVER['HTTP_NURISHD_SIGNATURE'] ?? null; if (!verify_signature($rawBody, $header, getenv('NURISHD_WEBHOOK_SECRET'))) { http_response_code(400); exit; } $event = json_decode($rawBody, true); // Handle by $event['id'] so a repeated delivery does no harm. http_response_code(200); ``` ## Test your check 1. In the console, select **Send test event** on your endpoint. Nurish'd sends a signed `ping`. 2. Confirm your code accepts it. 3. Change one byte of the body and confirm it fails. 4. Change `t` to a time six minutes old and confirm it fails. ## Roll a secret Roll a secret when it may have leaked, or on a schedule. Rolling keeps the old secret valid for 24 hours, so you do not miss events. 1. Roll the secret in the console, or call `PUT /developer/v1/webhook-endpoint/{endpoint_id}/secret/roll/document`. The answer holds the new secret in `secret`, and `endpoint.previous_secret_expires_at` says when the old one stops working. 2. For 24 hours, each delivery carries two `v1=` values. The code above accepts a delivery if either matches. 3. Deploy the new secret. While you do, deliveries verify with either secret. 4. After `previous_secret_expires_at`, only the new secret is valid. ```bash curl -X PUT https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN/secret/roll/document \ -H "X-Partner-API-Key: $NURISHD_API_KEY" ``` ```javascript const res = await fetch( 'https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN/secret/roll/document', { method: 'PUT', headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY }, }, ); const { endpoint, secret } = await res.json(); ``` ```python import os import requests res = requests.put( "https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN/secret/roll/document", headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]}, ) body = res.json() secret = body["secret"] ``` Your code needs one secret per endpoint. If you receive from several endpoints, look up the secret by endpoint. ## Next - [Webhooks](/docs/events/webhooks): create and manage endpoints. - [Events](/docs/events/events): the event body you verify. - [Errors](/docs/concepts/errors): handle failures when you fetch objects. --- # Members and roles The four company roles and what each can do, the five seats, inviting members and transferring ownership. You will know what each role can do, how seats work, and how to invite, remove or hand over ownership. ## Roles A member has one role in a company. | Can | Owner | Admin | Developer | Analyst | | ------------------------------------------------------------ | ----------------- | --------------------- | --------- | ------- | | Read the docs and use Sandbox keys | Yes | Yes | Yes | Yes | | See analytics and usage | Yes | Yes | Yes | Yes | | Create, narrow, roll and revoke Sandbox keys | Yes | Yes | Yes | No | | Create, narrow, roll and revoke Production keys | Yes | Yes | No | No | | Manage Sandbox webhook endpoints and reveal their secrets | Yes | Yes | Yes | No | | Manage Production webhook endpoints and reveal their secrets | Yes | Yes | No | No | | See the event list | Yes | Yes | Yes | No | | Invite and remove members, change roles | Yes | Yes, except the owner | No | No | | Set return URLs for the connect page | Yes | Yes | No | No | | Transfer ownership | Yes | No | No | No | | Change BAA, scopes, integrations or status | No, only Nurish'd | No | No | No | In plain words: - **Owner.** Everything an admin can do, plus transferring ownership. There is exactly one owner. - **Admin.** Runs the company's access: members, Production keys and webhooks, and return URLs. - **Developer.** Builds in the Sandbox: Sandbox keys and webhooks, and events. - **Analyst.** Reads analytics and usage. Cannot manage keys or webhooks, and cannot see events. When a role is not allowed to do something, the console says why the control is off. The server checks every call. ## Seats A company has at most five seats. A seat is taken by an active member or by a pending invite. The owner counts. Nurish'd staff never take a seat. - Removing a member or canceling a pending invite frees a seat. - An expired invite frees its seat when it expires. - When all five seats are taken, the console refuses a new invite. ## Invite a member Owners and admins invite members under **Members**. 1. Enter the email address and pick a role. 2. The invite is emailed. It expires after 7 days. 3. The person opens the link and asks for a code. We email a 6 digit code to the invited address. 4. They enter the code. A new person also enters their name, and an account is created for them. No password is needed. Someone who already has a password can sign in with it instead. 5. They press **Join** to accept the invite. 6. The code goes to the invited address, so a forwarded invite is useless to anyone else. An owner or admin can cancel a pending invite before it is accepted. One person can belong to one company in each region. ## Change a role or remove a member Owners and admins change roles and remove members. An admin cannot change or remove the owner. Nobody is changed to or from owner this way. Use a transfer. Removing a member does not touch the keys they made. Keys belong to the company. Revoke or roll a key yourself if the member knew it. See [Managing keys](/docs/console/managing-keys). ## Transfer ownership Only the owner can transfer ownership, to another active member. 1. Open **Members** and choose **Transfer ownership**. 2. Pick the member who becomes the owner. 3. Confirm. You become an admin, and they become the owner. There is never a moment with no owner or two owners. ## Leave a company Any member except the owner can leave a company. The owner must transfer ownership first. Nurish'd can also move ownership. ## Next - [Managing keys](/docs/console/managing-keys): who can do what per environment. - [Company settings](/docs/console/company-settings): what owners and admins set. - [Quickstart](/docs/get-started/quickstart): the first key. --- # Managing keys Create, narrow, roll and revoke API keys in the console, and who may do each in each environment. You will create an API key, narrow what it can do, roll it with a window and revoke it. Keys are managed in the console under **API keys**. The API has no route to create or revoke a key. It has one route to check the key you call it with. ## Who can do what | Action | Sandbox | Production | | ---------------------------- | ----------------------- | ------------ | | Create, narrow, roll, revoke | Owner, Admin, Developer | Owner, Admin | Use the environment switch at the top of the console to choose Sandbox or Production. Keys belong to the company, not to a member. ## Before you create a key - The company owner must have accepted the API terms. Until then, no key can be created. - A Production key can be created only after Nurish'd marks the company Live. ## Create a key 1. Choose the environment. 2. Select **Create key**. 3. Give the key a name that says what uses it, such as `order-service`. 4. Optionally narrow its scopes. See below. 5. Create it and copy the key. The full key is shown once. Copy it into your secret manager now. If you lose it, create a new key. ## Narrow scopes A key with no narrowed scopes follows the company's scopes. Pick fewer scopes to limit one key, for example `catalog:read` for a read-only job. - A key can never hold a scope the company lacks. - If Nurish'd removes a scope from the company, every key loses it. - The scopes you can pick are the company's. Confirm the result with `GET /developer/v1/key/get/document`. See [Scopes](/docs/concepts/scopes). ## Roll a key Rolling makes a new key and sets the old one to expire. Choose when the old one expires: | Window | Use it when | | ------ | --------------------------------------------------- | | Now | The old key leaked. Services using it fail at once. | | 1 hour | You can deploy fast. | | 1 day | The usual choice. | | 7 days | Many services share the key. | Copy the new key when it is shown, deploy it, check it, then let the old one expire. See [Authentication](/docs/concepts/authentication). ## Revoke a key Revoke a key to stop it for good. A revoked key answers `401 invalid_api_key`. You cannot restore it. Create a new key if you need one. A key that is expired or revoked and used for an action that needs an active key can also answer `409 key_not_active`. ## Next - [Authentication](/docs/concepts/authentication): the header and storing keys. - [Scopes](/docs/concepts/scopes): what to narrow to. - [Members and roles](/docs/console/members-and-roles): the permission table. --- # Company settings What Nurish'd controls on your company, and what owners and admins can set themselves. You will know which settings Nurish'd controls, which ones you control, and how to ask for a change. ## What Nurish'd controls You see these under **Settings**, read only. To change one, email `hello@nurishd.io`. | Setting | What it does | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | | Status | `Sandbox`, `Live` or `Suspended`. A Production key needs `Live`. A suspended company's keys stop working. | | BAA | The date your business associate agreement was signed. Care scopes need it. See [BAA handling](/docs/care/baa). | | Scopes | The API scopes granted to the company. Keys can only narrow them. See [Scopes](/docs/concepts/scopes). | | Rate limits | Calls per minute for each environment. Defaults are 25 in the Sandbox and 100 in Production. See [Rate limits](/docs/concepts/rate-limits). | | Integrations | Settings for integrations such as Shopify, when they are available. | Changes by Nurish'd take effect within a minute. The `status` of your company is also returned by `GET /developer/v1/key/get/document` in `company.status`. ## What owners and admins control ### Return URLs A return URL is where Nurish'd sends a customer or patient after the connect page. Only URLs you registered here are accepted. 1. Open **Settings** and find **Return URLs**. 2. Add the full URL, for example `https://shop.example.com/nurishd/return`. 3. Pass the same URL as `return_url` when you create a customer. A `return_url` that is not on the list answers `422 validation_error`. Owners and admins can add and remove return URLs. Developers and analysts cannot. Never trust the `status` in a return URL. See [Connections](/docs/concepts/connections). ### API terms The owner accepts the [Nurish'd API terms](https://www.nurishd.io/api-policy) the first time they sign in. The console stores the version, who accepted and when. No key can be created until the terms are accepted. When Nurish'd publishes a new version, the console asks again. Until it is accepted, calls can answer `403 api_terms_not_accepted`. ### Members and seats Owners and admins manage members and see how many of the five seats are used. See [Members and roles](/docs/console/members-and-roles). ## Next - [Members and roles](/docs/console/members-and-roles): who can do what. - [Managing keys](/docs/console/managing-keys): keys follow the company's scopes. - [Support](/docs/resources/support): ask for a change. --- # Changelog What has shipped in Nurish'd Connect, newest first. You will see what changed in the API and when. Additive changes to a version are listed here. Breaking changes ship only in a new version. See [Versioning](/docs/concepts/versioning). ## 2026-11-20: More limits per key - A burst limit: 120 calls in any 10 seconds in the Sandbox, 600 in Production. Calls you do not use add up, so a quiet key can go above its calls per minute for a moment. - The report routes and the event list have their own limit: 10 calls per minute in the Sandbox, 30 in Production. - A key can have 10 calls in progress at once in the Sandbox, 50 in Production. - `RateLimit-Remaining` can now be above `RateLimit-Limit`. Every refusal is still `429 rate_limited` with `Retry-After`. See [Rate limits](/docs/concepts/rate-limits). - A webhook endpoint has 5 seconds to answer a delivery. It was 10. ## 2026-11-18: A care patient needs an address - `POST /care/v1/patient/create/document` now requires `address` (`line1`, `city`, `state`, `postal_code` and `country`; `line2` stays optional). A call without it answers `422 validation_error`. Before, such a call was refused with a message that named no field. - Booking create answers `409 service_not_bookable` for a specialist or a service that does not exist. `404 not_found` there now only means the patient has no care connection with your company. ## 2026-11-18: Order events, order refusals and stricter inputs - Three new event types: `order.shipped`, `order.delivered` and `order.refunded`. They carry the order as `data.id` and the `customer`, like the other order events. - A new `422` code, `vendor_not_allowed_for_customer`, for a customer whose account is limited to other vendors. Order create refuses with `delivery_not_available`, `product_not_available`, `order_limits_not_met` or `vendor_not_allowed_for_customer`, each for its own reason. `delivery_not_available` now only means the vendor does not deliver there or then. - Order create checks the vendor first: a vendor that does not exist, is not live, is archived or is not enabled for your company now answers `404 not_found`. - Delivery days are strict `YYYY-MM-DD`: `from`, `to` and the `{date}` path segment of the delivery-date routes, and `order_delivery_date`. `to` is at most 60 days after `from` and at most 60 days from now, otherwise `400`. The zone lookup compares `city`, `state` and `country` exactly, letter case included. - The delivery address of an order has its own limits (`OrderShippingAddressInput`). - Every id in a path, the `vendor` query parameter and `order_vendor` has a format. An id that does not fit is a `422 validation_error`. ## 2026-11-17: Error code renamed - The `409` code `patient_already_connected` is now `person_already_connected`. It is the same refusal, for a customer or a patient: the email is already connected under a different `external_id`. Update any code that matches on the old value. - A connection event carries `data.customer` for a meals connection and `data.patient` for a care connection. ## 2026-11-11: Field names now match Nurish'd's own resource names Every public resource now carries the field names, the nesting and the enum values of the internal resource. This is a change to the shapes in the Sandbox release. Update the code that reads answers and sends bodies. The most visible renames: **Meals** - Products: `id`, `name`, `price`, `type` become `product_id`, `product_name`, `product_price` and `product_type`. Types are `Meal`, `Bulk` and `Misc`, and collections are `Breakfast`, `Lunch` and so on. Nutrition moves to `product_nutrition`, with values such as `total_calories__KCAL`. - Vendors and zones: `vendor_id`, `vendor_name`, `vendor_address`, `vendor_minimum_order_items`, `zone_id` and `zone_delivery_days`. - Delivery dates: the list answers `valid_delivery_dates` as datetimes. One date answers `order_cutoff_date`, `menu`, `all_unique_product_ids` and `is_given_date_blackout`. `is_available` is gone. Menu status is `in_production`, `upcoming`, `expired` or `not_in_production`. - Customers and connections: the customer id is `user`. A connection has `connection_id`, `company_id`, `user`, `created_at`, `approved_at` and `revoked_at`. The link expiry is `connect_url_expires_at`. - Orders: create takes `user`, `order_vendor`, `order_delivery_date`, `order_shipping_address`, `line_items` (`line_item_product_id`, `line_quantity`), `order_contact_email`, `order_contact_phone` and `order_customer_notes`. The answer has `order_id`, `order_financial_status`, `order_fulfillment_status` and `order_delivery_status` with the internal values, money fields such as `order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING`, and `stripe_payment_intent` with `stripe_publishable_key` while the payment is pending. **Care** - Patients: the patient id is `user`, with the same connection fields as meals. - Specialists and services: `specialist_id`, `specialist_first_name`, `specialist_locations`, `service_id`, `service_price_in_cents` and `service_mode_of_delivery`. Open times use `start_time`, `end_time` and `duration_in_minutes`. - Bookings: create takes `user`, `specialist_id`, `service_id`, `start_time` and `client_note`. The answer has `booking_id`, `start_date`, `end_date`, `specialist_snapshot` and `service_snapshot`. Status is `booked`, `meeting_rescheduled`, `meeting_completed`, `meeting_cancelled` or `no_show`. - Reports: `report_id`, `signed_at` and sections with `section_id`, `section_name`, `section_type` and `section_content`. - Health profiles: `has_diabetes` with `diabetes_information`, `has_heart_condition` with `heart_condition_information`, `has_other_diseases` with `other_diseases_notes`, and `general_health_data` for the measurement. The update takes the flags. - Saved cards: `id`, `card` (`brand`, `last4`, `exp_month`, `exp_year`) and `is_default`. A card setup answers `id`, `client_secret`, `status` and `stripe_publishable_key`. **Developer tools** - Key check: flat fields `key_id`, `name`, `mode`, `scopes`, `company_id`, `company_name`, `company_status` and `rate_limit_per_minute`. - Webhook endpoints: `endpoint_id`, `company_id`, `is_enabled`, `previous_secret_expires_at`, `created_at` and `updated_at`. Update takes `is_enabled`. - The Sandbox test helper that completes a booking and signs a sample report is available. **New errors** - Creating a customer or patient can answer `409 external_id_conflict` or `409 patient_already_connected`. - Booking a patient with no saved card answers `409 payment_method_required`. Paths, methods, events, the error shape and its codes, and the paging fields did not change. Filter names did not change either, but filter values are now the internal values, for example `type=Meal` and `status=meeting_cancelled`. ## 2026-11-11: care and meals orders **Care (`/care/v1`)** - Patients and connections: create a patient, read a patient, read a connection and revoke a connection. Need `patient:write`. See [Connecting a patient](/docs/care/connecting-a-patient). - Specialists, services and availability: list and read specialists, list their services and read open times up to 31 days. Need `specialist:read`. - Bookings: book, list, read and cancel visits. Need `booking:write` and `booking:read`. See [Booking a visit](/docs/care/booking-a-visit). **Meals (`/meals/v1`)** - Orders: place an order for a connected customer, list orders and read one. The answer carries the Stripe payment for Stripe.js. Need `order:write` and `order:read`. See [Orders](/docs/meals/orders). **Saved cards** - Saved cards for patients and customers: start a card setup, confirm it after Stripe.js, and list saved cards. Care routes need `patient:write`. Meals routes need `order:write` and, to list, `order:read`. See [Saving a card](/docs/care/saving-a-card) and [Saving a card for a customer](/docs/meals/saving-a-card). - A card is required before a visit can be booked. Booking a patient with no default card answers `409 payment_method_required` and books nothing. The order of calls is: connect the patient, save a card, book. **Events** - `booking.created`, `booking.canceled`, `order.created`, `order.paid`, `order.fulfilled` and `order.canceled` are raised. Order events carry a `customer` id. **Visit reports and health profiles** - Visit reports: list signed reports of your bookings, read one with its shared sections and fetch the time-limited link to a section file. Need `report:read`. `report.signed` is raised for visits your company booked. See [Visit reports](/docs/care/reports). - Health profiles: read a patient's profile and replace it. An update is a full replace, the first save needs a measurement (`general_health_data`), and a patient can have one measurement every 24 hours. Need `health-profile:read` and `health-profile:write`. See [Health profiles](/docs/care/health-profiles). **Webhook delivery** - Delivery is live. Each delivery carries a final `Nurishd-Signature` header: `t=,v1=.">`, with a second `v1=` value for 24 hours after a roll. Failed deliveries are retried with backoff for up to three days. See [Verifying signatures](/docs/events/verifying-signatures). ## 2026-11-11: first Sandbox release The first release of Nurish'd Connect is available in the Sandbox. **Developer tools (`/developer/v1`)** - Check your API key: `GET /developer/v1/key/get/document`. - List and read events: `GET /developer/v1/event/query/documents` and `GET /developer/v1/event/{event_id}/get/document`. - Create, list, change, delete and roll the secret of webhook endpoints. **Meals (`/meals/v1`)** - Catalog: vendors, menus, products, delivery zones and delivery dates. Needs `catalog:read`. - Customers and connections: create a customer, read a customer, read a connection and revoke a connection. **Console** - Create, narrow, roll and revoke API keys. - Manage webhook endpoints and see events. - Invite members with four roles, up to five seats. **Not yet available** - Webhook delivery, visit reports and health profiles shipped after this release. See the entry above. - Production keys need Nurish'd to mark your company Live. ## Next - [Quickstart](/docs/get-started/quickstart): make your first call. - [Versioning](/docs/concepts/versioning): how changes ship. - [Support](/docs/resources/support): ask a question. --- # Support How to contact Nurish'd about the API, what to send, and what never to send. You will know how to reach Nurish'd and what to include so a problem can be solved in one reply. ## Contact Email `hello@nurishd.io`. Use it for questions, bugs, a higher rate limit, going live, and a BAA. ## What to send - **The request id.** Every answer carries it in the `X-Request-Id` header, and every error body repeats it as `request_id`. With it, Nurish'd can find exactly one call. - The environment: Sandbox or Production. - The method and path, such as `GET /meals/v1/zone/query/documents`. - The status and the error `code`. - When it happened, with a time zone. - What you expected, and what you got. - The last four characters of the key, or its name in the console. ```text Request id: req-0001 Environment: Sandbox Call: GET /meals/v1/zone/query/documents (city, state, country) Result: 422 validation_error Time: 2026-11-30 15:04 UTC Expected: the zones that serve Mississauga, ON, CA ``` ## What never to send > **Warning.** Never send an API key, a signing secret, or patient data to support. Not in an email, a ticket, a chat or a screenshot. - **API keys and signing secrets.** If one leaked, revoke or roll it first. See [Managing keys](/docs/console/managing-keys). - **Patient data.** No names, emails, dates of birth, bookings, reports or health profiles. Send ids and request ids instead. - **Full response bodies** from care routes. Nurish'd staff never ask for your key. ## Before you write - Look up the code in [Errors](/docs/concepts/errors). - Check your key with `GET /developer/v1/key/get/document`. - Check the [changelog](/docs/resources/changelog). ## Next - [Errors](/docs/concepts/errors): every code. - [Authentication](/docs/concepts/authentication): key problems. - [Changelog](/docs/resources/changelog): what has shipped. --- # API reference: Nurish'd Connect API ### POST /care/v1/booking/create/document Book a visit. Books one of the open times of a service for a patient. The patient must have an active connection with your company that allows bookings. Insurance cannot be used for a booking made through this API. The order of calls is: connect the patient, save a card, book. A visit charges nothing when it is booked; the visit, a late-cancellation fee and a no-show fee are charged later to the patient's default card, so a patient with no default card cannot be booked. Save one first with `POST /care/v1/patient/{patient_id}/payment-method/setup/create/document` and its confirm route. Booking the same patient, specialist and start again returns the first booking, so a retry is safe. A new booking raises one `booking.created` event; a repeat raises none. Answers: - `404` when the patient has no connection with your company that allows care. - `403 connection_scope_not_granted` when the patient did not allow bookings. - `409 connection_not_active` when the connection is pending or was revoked. - `409 payment_method_required` when the patient has no card saved to their account. Nothing is booked. - `409 agreements_not_signed` when the patient has not signed the agreements a visit needs. - `409 service_not_bookable` when the service cannot be booked online, or the specialist or the service does not exist. - `409 not_licensed_here` when the specialist cannot serve the booking yet. - `409 slot_taken` when the time is no longer open. Needs the `booking:write` scope. Request body: `BookingCreateInput` Responses: - `201` Successful Response: `BookingOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/booking/query/documents List bookings. Returns a page of the visits your company booked, newest visit first. Visits booked by the patient themselves or by another company are never listed, and neither are visits of patients whose connection with your company is no longer active. The list has no note; read one booking to get it. The `status` filter works on the status last seen for each booking, which is refreshed whenever a booking is read, so a visit that changed outside this API can show under its old status until it is read. The status of every booking in the answer is current. Query parameters: - patient: Keep only the visits of this patient. - status: Keep only visits in this status: `booked`, `meeting_rescheduled`, `meeting_completed`, `meeting_cancelled` or `no_show`. - from: Keep only visits that start at or after this time, with a UTC offset. - to: Keep only visits that start at or before this time, with a UTC offset. - page: The page number, from 1. - size: The page size, at most 50. Needs the `booking:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `patient` | query | string (uuid) | No | Keep only the visits of this patient. | | `status` | query | BookingStatusEnum | No | Keep only visits in this status: `booked`, `meeting_rescheduled`, `meeting_completed`, `meeting_cancelled` or `no_show`. | | `from` | query | string (date-time) | No | Keep only visits that start at or after this time, with a UTC offset. | | `to` | query | string (date-time) | No | Keep only visits that start at or before this time, with a UTC offset. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `BookingPageOutput` - `400` The request cannot be processed as sent, for example a range that ends before it starts.: `Error` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### PUT /care/v1/booking/{booking_id}/cancel/document Cancel a booking. Cancels a visit your company booked. WARNING: a visit canceled less than 24 hours before it starts may be charged Nurish'd's late-cancellation fee, billed to the patient. Tell the patient before you cancel. A booking that is already canceled, completed or past answers `409 booking_not_cancelable`. A cancellation raises one `booking.canceled` event. The body is optional. Answers `404` for a visit your company did not book, and `409 connection_not_active` when the patient's connection with your company was revoked. Needs the `booking:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `booking_id` | path | string | Yes | The ID of the booking. | Request body: `BookingCancelInput` Responses: - `200` Successful Response: `BookingOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/booking/{booking_id}/get/document Get a booking. Returns one visit your company booked, with the note. A visit the patient booked themselves, or that another company booked, answers `404`. Answers `409 connection_not_active` when the patient's connection with your company was revoked: the visit stays booked, but you can no longer read or change it. If the visit was canceled by the patient or the specialist, the answer says so and a `booking.canceled` event is raised once. Needs the `booking:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `booking_id` | path | string | Yes | The ID of the booking. | Responses: - `200` Successful Response: `BookingOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/connection/{connection_id}/get/document Get a connection. Returns a connection between your company and a patient, with its status brought up to date. Nothing can be booked for the patient until the status is `active`. Read the connection, or trust the `connection.approved` event, to learn that the patient approved; never trust the `status` in the return URL. A connection that does not exist, is not a care connection, or belongs to another company or mode, answers `not_found`. Needs the `patient:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `connection_id` | path | string | Yes | The ID of the connection, as `create` answered it. | Responses: - `200` Successful Response: `CareConnectionOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### PUT /care/v1/connection/{connection_id}/revoke/document Revoke a connection. Ends a connection. Visits already booked stay booked, but can no longer be read or changed through your key. To connect again, call create with the same `external_id` and send the patient to the new `connect_url`. Raises a `connection.revoked` event. A connection that is already revoked or declined answers `connection_not_active`. Needs the `patient:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `connection_id` | path | string | Yes | The ID of the connection to end. | Responses: - `200` Successful Response: `CareConnectionOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### POST /care/v1/patient/create/document Create a patient. Creates a patient, or connects to the patient's existing Nurish'd account, and starts a connection with them. Nothing can be booked for a patient until they approve the connection, so the answer carries a `connect_url`: - Send the patient to `connect_url` as a full page or a new tab. Never open it inside a frame or a web view. - The patient confirms with a code sent to the email on their Nurish'd account, signs the health privacy agreement and the telehealth consent, and approves. - The link is valid for 24 hours and works once. Calling create again with the same `external_id` returns the same patient and a fresh link. - The connection is `pending` until the patient approves it. Nothing can be booked for the patient until the connection is `active`. - To find out, trust the `connection.approved` event or read the connection. Never trust the `status` in the return URL, because anyone can edit a URL. The address is required: a dietitian must be licensed in the patient's province, and a visit cannot be booked for a patient with no address. The patient is asked to allow every care permission your key can use: `care.bookings` when it holds `booking:write`, `care.reports` when it holds `report:read`, and `care.health-profile` when it holds `health-profile:read` or `health-profile:write`. A key with none of those is refused with `scope_not_granted`. The answer never says whether the email already had a Nurish'd account. A patient is known to your company under one `external_id`. Two requests are refused with a `409` and create nothing: `external_id_conflict` when the `external_id` already belongs to a patient with a different email, and `person_already_connected` when the email is already connected under a different `external_id`. To change the id you use for a patient, keep using the first one. Needs the `patient:write` scope, which needs a signed BAA. Request body: `PatientCreateInput` Responses: - `200` Successful Response: `PatientOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/patient/{patient_id}/get/document Get a patient. Returns a patient and their connection with your company, with the connection's status brought up to date. `connect_url` and `connect_url_expires_at` are always `null` here: call create again with the same `external_id` for a fresh link. A patient that does not exist, or belongs to another company or mode, answers `not_found`. Needs the `patient:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `patient_id` | path | string (uuid) | Yes | The ID of the patient, as `create` answered it. | Responses: - `200` Successful Response: `PatientOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/patient/{patient_id}/health-profile/get/document Get the health profile of a patient. Returns the health profile of a patient with their latest measurement. The patient must have an active connection with your company that allows the health profile: a pending or revoked connection answers `connection_not_active`, a connection made without the health profile permission answers `connection_scope_not_granted`, and an unknown patient, or one of another company or mode, answers `not_found`. A patient who has no health profile yet answers `health_profile_not_found`; create it with the update route. `diabetes_information` and `heart_condition_information` are `null` when none was saved, and `general_health_data`, the latest measurement, is `null` when there is none. Needs the `health-profile:read` scope, which needs a signed BAA. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `patient_id` | path | string (uuid) | Yes | The ID of the patient, as `create` answered it. | Responses: - `200` Successful Response: `HealthProfileOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### PUT /care/v1/patient/{patient_id}/health-profile/update/document Save the health profile of a patient. Saves the whole health profile of a patient, and answers it as `get` would. It creates the profile the first time and replaces it every time after. **This is a full replace: send the whole profile; a field you leave out is cleared.** To change one thing, read the profile, change it and send all of it back. A flag you leave out is false. `has_diabetes`, `has_heart_condition` and `has_other_diseases` set to true need `diabetes_information`, `heart_condition_information` and `other_diseases_notes` respectively, or the answer is 422; a block sent with its flag false is not refused and is saved as sent. `general_health_data` adds a new measurement (height, weight, activity, goal and more) to the patient's history; `get` answers the latest one. It is required the first time, because a profile cannot be created without one: without it a patient who has no profile yet answers `measurement_required`. A patient can have one measurement every 24 hours: a `general_health_data` sent sooner answers `measurement_too_recent`, and nothing is saved. Leave `general_health_data` out to change the profile alone. The patient must have an active connection with your company that allows the health profile (see `get`). A body that fails validation answers 422 and saves nothing. Needs the `health-profile:write` scope, which needs a signed BAA. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `patient_id` | path | string (uuid) | Yes | The ID of the patient, as `create` answered it. | Request body: `HealthProfileUpdateInput` Responses: - `200` Successful Response: `HealthProfileOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/patient/{patient_id}/payment-method/query/documents List a patient's saved cards. Returns the cards saved to the patient's Nurish'd account, at most 10, in one page. Each card has `id`, `card` (`brand`, `exp_month`, `exp_year` and `last4`) and `is_default`, which is `true` for the card visits and fees are charged to. The patient can also add, remove and choose cards in their own account, so the list can change without you. A patient with no card gets an empty list. Answers `404` when the patient has no connection with your company that allows care, `403 connection_scope_not_granted` when the patient did not allow bookings, and `409 connection_not_active` when the connection is pending or was revoked. Needs the `patient:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `patient_id` | path | string (uuid) | Yes | The ID of the patient, as the create-patient route answered it. | Responses: - `200` Successful Response: `PaymentMethodPageOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### POST /care/v1/patient/{patient_id}/payment-method/setup/create/document Start saving a card for a patient. Starts saving a card to the patient's Nurish'd account. A visit cannot be booked for a patient until a card is saved, because the visit, a late-cancellation fee and a no-show fee are charged later to the patient's default card. The order of calls is: connect the patient, save a card, book. The card number never reaches your server or ours. Your page loads Stripe.js with the answered `stripe_publishable_key` and confirms the card with the answered `client_secret`: the patient types the card into Stripe's own form on your page. Then call the confirm route with the answered `id`. Never log the client secret. The card is saved to the patient's Nurish'd account and may be charged for visits, late- cancellation fees and no-show fees. Tell the patient so before they type the card in. Calling it again returns the same open setup while it is less than a day old. The patient must have an active connection with your company that allows bookings. Answers `404` when the patient has no connection with your company that allows care, `403 connection_scope_not_granted` when the patient did not allow bookings, and `409 connection_not_active` when the connection is pending or was revoked. Needs the `patient:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `patient_id` | path | string (uuid) | Yes | The ID of the patient, as the create-patient route answered it. | Responses: - `200` Successful Response: `PaymentMethodSetupOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### PUT /care/v1/patient/{patient_id}/payment-method/setup/{setup_id}/confirm/document Finish saving a card for a patient. Call it after Stripe.js confirmed the card on your page. It checks the setup, makes sure the card is recorded on the patient's Nurish'd account, and answers the card. When the patient had no default card, the card becomes their default card, the one visits and fees are charged to. A patient who already has a default card keeps it, and the answer says `is_default: false`. Calling it again for the same setup is safe, and it does not wait for any notification, so call it right after the card form says it worked. Answers `409 payment_method_setup_incomplete` when the card form has not confirmed the card yet, `404` for a setup that is not this patient's, and the same `404`, `403` and `409` as the start route for the patient's connection. Needs the `patient:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `patient_id` | path | string (uuid) | Yes | The ID of the patient, as the create-patient route answered it. | | `setup_id` | path | string | Yes | The ID of the setup, as the start route answered it. | Responses: - `200` Successful Response: `PaymentMethodOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/report/query/documents List reports. Returns a page of the signed reports of the visits your company booked, newest signed first. A report of a visit the patient booked themselves, or that another company booked, is never listed, and neither is a report of a patient whose connection with your company is no longer active. The list is thin: read one report to get its sections. You learn that a report exists from the `report.signed` event. When you ask for one `booking` and no report of it is known yet, the answer also looks for a signed report of that visit, so a report whose event you missed still shows up, and its event is raised once. Query parameters: - patient: Keep only the reports of this patient. - booking: Keep only the reports of this booking. - from: Keep only reports signed at or after this time, with a UTC offset. - to: Keep only reports signed at or before this time, with a UTC offset. - page: The page number, from 1. - size: The page size, at most 50. Needs the `report:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `patient` | query | string (uuid) | No | Keep only the reports of this patient. | | `booking` | query | string | No | Keep only the reports of this booking. | | `from` | query | string (date-time) | No | Keep only reports signed at or after this time, with a UTC offset. | | `to` | query | string (date-time) | No | Keep only reports signed at or before this time, with a UTC offset. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `ReportPageOutput` - `400` The request cannot be processed as sent, for example a range that ends before it starts.: `Error` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/report/{report_id}/get/document Get a report. Returns one signed report of a visit your company booked, as the patient sees it: only the sections the specialist shared with the patient. The patient's own details, the specialist's signature and any private notes are never part of it. A section of type `image` or `pdf` has `has_file: true`; ask for a time-limited link to read its file. Answers `404` for a report of a visit the patient booked themselves, that another company booked, or that does not exist; `409 connection_not_active` when the patient's connection with your company was revoked; `403 connection_scope_not_granted` when the patient does not share reports. Needs the `report:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `report_id` | path | string | Yes | The ID of the report. | Responses: - `200` Successful Response: `ReportOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/report/{report_id}/section/{section_id}/file/get/document Get the file of a report section. Returns a link to the file of an `image` or `pdf` section of a report (the sections with `has_file: true`). The link works for a short time only: fetch the file at once and do not store the link. Ask again when you need the file again. Answers `404` for a report your company has no access to, a section the specialist did not share, and a section without a file; `409 connection_not_active` when the patient's connection with your company was revoked; `403 connection_scope_not_granted` when the patient does not share reports. Needs the `report:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `report_id` | path | string | Yes | The ID of the report. | | `section_id` | path | string | Yes | The ID of the section whose file to read. | Responses: - `200` Successful Response: `ReportFileOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/specialist/query/documents List specialists. Returns a page of the specialists you can book, by name. Specialists that are not live yet, that are hidden or that were retired are never listed. The list leaves out the long description of each specialist; read one specialist to get it. Listing needs no patient and no business associate agreement. Query parameters: - type: Keep only this kind of specialist: `Dietitian`, `Certified Nutrition Specialist` or `Physical Trainer`. - language: Keep only specialists who speak this language, for example `Spanish`. - specialization: Keep only specialists with this specialization, for example `Weight Loss/Management`. - state: Keep only specialists who practise in this province, as two capital letters, for example `ON`. The `specialist_locations` of a specialist then show only the places in that province. - name: Keep only specialists whose name starts with this text. One word matches the start of the last name; with more words, the first word matches the start of the first name and the rest the start of the last name. Not case sensitive. - page: The page number, from 1. - size: The page size, at most 50. Needs the `specialist:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `type` | query | SpecialistTypeEnum | No | Keep only this kind of specialist: `Dietitian`, `Certified Nutrition Specialist` or `Physical Trainer`. | | `language` | query | string | No | Keep only specialists who speak this language, for example `Spanish`. | | `specialization` | query | SpecializationEnum | No | Keep only specialists with this specialization, for example `Weight Loss/Management`. | | `state` | query | string | No | Keep only specialists who practise in this province, as two capital letters, for example `ON`. | | `name` | query | string | No | Keep only specialists whose name starts with this text. Not case sensitive. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `SpecialistPageOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/specialist/{specialist_id}/get/document Get a specialist. Returns one specialist with the long description. Answers `404` when the specialist does not exist, is not live yet, is hidden or was retired. Needs the `specialist:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `specialist_id` | path | string (uuid) | Yes | The ID of the specialist. | Responses: - `200` Successful Response: `SpecialistOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/specialist/{specialist_id}/service/query/documents List the services of a specialist. Returns a page of the services of one specialist that you can book. Services that are not live yet or that were retired are never listed. Answers `404` when the specialist does not exist, is not live yet, is hidden or was retired. Query parameters: - page: The page number, from 1. - size: The page size, at most 50. Needs the `specialist:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `specialist_id` | path | string (uuid) | Yes | The ID of the specialist. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `ServicePageOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /care/v1/specialist/{specialist_id}/service/{service_id}/availability/query/documents List the open times of a service. Returns the times a patient can still book for one service of a specialist, earliest first, in UTC. Pass one of these times as the `start` of a booking. Needs no patient and no business associate agreement. The range must start before it ends and be at most 31 days long, otherwise the answer is `422 invalid_time_range`. A `from` in the past is moved up to the present, and the answer says the range that was searched. Answers `409 service_not_bookable` when the service cannot be booked online, for example a service delivered in person, and `404` when the specialist does not exist, is not live yet, is hidden or was retired. Query parameters: - from: The start of the range, with a UTC offset, for example `2026-06-01T00:00:00Z`. - to: The end of the range, with a UTC offset. Needs the `specialist:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `specialist_id` | path | string (uuid) | Yes | The ID of the specialist. | | `service_id` | path | string | Yes | The ID of the service. | | `from` | query | string (date-time) | Yes | The start of the range, with a UTC offset, for example `2026-06-01T00:00:00Z`. | | `to` | query | string (date-time) | Yes | The end of the range, with a UTC offset. At most 31 days after `from`. | Responses: - `200` Successful Response: `AvailabilityOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /developer/v1/event/query/documents List events. Returns what happened to your company's connections, bookings, reports and orders, newest first. An event is thin: it holds a type and ids, never the object itself, so fetch the object with your API key. Only events of the last 30 days are listed, only those made with the mode of your key, and only the types your key's scopes allow. The same events are what a webhook endpoint receives. Query parameters: - type: Keep only events of this type, such as `report.signed`. - from: Keep only events created at or after this time (ISO 8601 with a time zone). - to: Keep only events created at or before this time (ISO 8601 with a time zone). - page: The page number, from 1. - size: The page size, at most 50. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `type` | query | EventTypeEnum | No | Keep only events of this type. | | `from` | query | string (date-time) | No | Keep only events created at or after this time. It must carry a time zone. | | `to` | query | string (date-time) | No | Keep only events created at or before this time. It must carry a time zone. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `EventPageOutput` - `400` The request cannot be processed as sent, for example a range that ends before it starts.: `Error` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /developer/v1/event/{event_id}/get/document Get an event. Returns one event. An event is thin: it holds a type and ids, never the object itself, so fetch the object with your API key. An event that does not exist, belongs to another company or mode, or is of a type your key's scopes do not allow answers `not_found`. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `event_id` | path | string | Yes | The ID of the event, such as `evt_...`. | Responses: - `200` Successful Response: `EventOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /developer/v1/key/get/document Check your API key. Returns the API key the request was made with: its name, its mode (`test` or `prod`), what it may do, the company it belongs to and the number of calls per minute it may make. Use it to confirm that a key works and has the access you expect. It needs no scope. Responses: - `200` Successful Response: `KeyOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### POST /developer/v1/test-helper/booking/{booking_id}/complete/document Complete a test booking. Sandbox only. There are no real visits in the sandbox, so nothing ever produces a signed report. This route finishes a test booking for you: it marks the visit `meeting_completed` and signs a sample report, so you can try the `report.signed` event and the report routes from start to end. The content of the sample report is invented. It works only with a test key (`nk-test-`). A prod key (`nk-prod-`) answers `403 test_mode_only` and nothing happens. The `report.signed` event follows shortly after this route answers. The booking must be one your company made with a test key: otherwise the answer is `404`. A booking that was canceled, or is already completed, answers `409 booking_not_completable`. Needs the `booking:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `booking_id` | path | string | Yes | The ID of the test booking. | Responses: - `200` Successful Response: `TestHelperBookingCompleteOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### POST /developer/v1/webhook-endpoint/create/document Create a webhook endpoint. Registers an HTTPS address that receives the event types you choose, with a signing secret of its own. The secret is shown here, in `secret`, and can be read again in the developer console. Verify every delivery with it. The URL must be public: `https` only, no user name or password, no fragment, no `localhost` or private IP address. Choose at least one event type, each once; `ping` cannot be chosen. Your key's scopes must let it see every type you choose, otherwise the call answers `scope_not_granted`. A company has at most 10 endpoints per mode; the 11th answers `webhook_endpoint_limit_reached`. The endpoint is made in the mode of your key. Events are thin: an event holds a type and ids, never the object itself, so fetch the object with your API key. Each endpoint has its own signing secret; verify every delivery with it. Request body: `WebhookEndpointCreateInput` Responses: - `201` Successful Response: `WebhookEndpointWithSecretOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /developer/v1/webhook-endpoint/query/documents List webhook endpoints. Returns your company's webhook endpoints in the mode of your key, newest first. The signing secret is not listed: only its last four characters. Query parameters: - page: The page number, from 1. - size: The page size, at most 50. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `WebhookEndpointPageOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### DELETE /developer/v1/webhook-endpoint/{endpoint_id}/delete/document Delete a webhook endpoint. Deletes a webhook endpoint. Events are no longer sent to it. An endpoint of another mode answers `not_found`. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `endpoint_id` | path | string | Yes | The ID of the webhook endpoint, such as `whe-...`. | Responses: - `200` Successful Response: `WebhookEndpointDeleteOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### PUT /developer/v1/webhook-endpoint/{endpoint_id}/secret/roll/document Replace the signing secret of a webhook endpoint. Makes a new signing secret at once and returns it in `secret`. After a roll both secrets are valid for 24 hours, so you can switch over without missing a delivery; then the old one stops working. `previous_secret_expires_at` says when. Each endpoint has one secret; verify every delivery with it. The secret can also be read in the developer console. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `endpoint_id` | path | string | Yes | The ID of the webhook endpoint, such as `whe-...`. | Responses: - `200` Successful Response: `WebhookEndpointWithSecretOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### PUT /developer/v1/webhook-endpoint/{endpoint_id}/update/document Change a webhook endpoint. Changes the fields you send and leaves the others as they are. Send `description` as `null` to clear it. Send `is_enabled: false` to pause deliveries. The same rules as on create apply to `url` and `events`. An endpoint of another mode answers `not_found`. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `endpoint_id` | path | string | Yes | The ID of the webhook endpoint, such as `whe-...`. | Request body: `WebhookEndpointUpdateInput` Responses: - `200` Successful Response: `WebhookEndpointOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/connection/{connection_id}/get/document Get a connection. Returns a connection between your company and a customer, with its status brought up to date. Nothing can be ordered for the customer until the status is `active`. Read the connection, or trust the `connection.approved` event, to learn that the customer approved; never trust the `status` in the return URL. A connection that does not exist, or belongs to another company or mode, answers `not_found`. Needs the `order:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `connection_id` | path | string | Yes | The ID of the connection, as `create` answered it. | Responses: - `200` Successful Response: `MealsConnectionOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### PUT /meals/v1/connection/{connection_id}/revoke/document Revoke a connection. Ends a connection. Nothing can be ordered for the customer afterwards; to connect again, call create with the same `external_id` and send the customer to the new `connect_url`. Raises a `connection.revoked` event. A connection that is already revoked or declined answers `connection_not_active`. Needs the `order:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `connection_id` | path | string | Yes | The ID of the connection to end. | Responses: - `200` Successful Response: `MealsConnectionOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### POST /meals/v1/customer/create/document Create a customer. Creates a customer and starts a connection with them. Nothing can be ordered for a customer until they approve the connection, so the answer carries a `connect_url`: - Send the customer to `connect_url` as a full page or a new tab. Never open it inside a frame or a web view. - The link is valid for 24 hours and works once. - The connection is `pending` until the customer approves it. Nothing can be ordered for the customer until the connection is `active`. - To find out, trust the `connection.approved` event or read the connection. Never trust the `status` in the return URL, because anyone can edit a URL. Calling create again with the same `external_id` returns the same customer and a fresh link. The answer never says whether the email already had a Nurish'd account. A customer is known to your company under one `external_id`. Two requests are refused with a `409` and create nothing: `external_id_conflict` when the `external_id` already belongs to a customer with a different email, and `person_already_connected` when the email is already connected under a different `external_id`. To change the id you use for a customer, keep using the first one. Needs the `order:write` scope. Request body: `CustomerCreateInput` Responses: - `200` Successful Response: `CustomerOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/customer/{customer_id}/get/document Get a customer. Returns a customer and their connection with your company, with the connection's status brought up to date. `connect_url` and `connect_url_expires_at` are always `null` here: call create again with the same `external_id` for a fresh link. A customer that does not exist, or belongs to another company or mode, answers `not_found`. Needs the `order:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `customer_id` | path | string (uuid) | Yes | The ID of the customer, as `create` answered it. | Responses: - `200` Successful Response: `CustomerOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/customer/{customer_id}/payment-method/query/documents List a customer's saved cards. Returns the cards saved to the customer's Nurish'd account, at most 10, in one page. Each card has `id`, `card` (`brand`, `exp_month`, `exp_year` and `last4`) and `is_default`, which is `true` for the customer's default card. The customer can also add, remove and choose cards in their own account, so the list can change without you. A customer with no card gets an empty list. Answers `404` when the customer has no connection with your company that allows meals, `403 connection_scope_not_granted` when the customer did not allow orders, and `409 connection_not_active` when the connection is pending or was revoked. Needs the `order:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `customer_id` | path | string (uuid) | Yes | The ID of the customer, as the create-customer route answered it. | Responses: - `200` Successful Response: `PaymentMethodPageOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### POST /meals/v1/customer/{customer_id}/payment-method/setup/create/document Start saving a card for a customer. Starts saving a card to the customer's Nurish'd account, so the customer can pay for orders you place for them without typing the card in each time. The card number never reaches your server or ours. Your page loads Stripe.js with the answered `stripe_publishable_key` and confirms the card with the answered `client_secret`: the customer types the card into Stripe's own form on your page. Then call the confirm route with the answered `id`. Never log the client secret. The card is saved to the customer's Nurish'd account and may be charged for orders the customer confirms. Tell the customer so before they type the card in. Calling it again returns the same open setup while it is less than a day old. The customer must have an active connection with your company that allows orders. Answers `404` when the customer has no connection with your company that allows meals, `403 connection_scope_not_granted` when the customer did not allow orders, and `409 connection_not_active` when the connection is pending or was revoked. Needs the `order:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `customer_id` | path | string (uuid) | Yes | The ID of the customer, as the create-customer route answered it. | Responses: - `200` Successful Response: `PaymentMethodSetupOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### PUT /meals/v1/customer/{customer_id}/payment-method/setup/{setup_id}/confirm/document Finish saving a card for a customer. Call it after Stripe.js confirmed the card on your page. It checks the setup, makes sure the card is recorded on the customer's Nurish'd account, and answers the card. When the customer had no default card, the card becomes their default card. A customer who already has a default card keeps it, and the answer says `is_default: false`. Calling it again for the same setup is safe, and it does not wait for any notification, so call it right after the card form says it worked. Answers `409 payment_method_setup_incomplete` when the card form has not confirmed the card yet, `404` for a setup that is not this customer's, and the same `404`, `403` and `409` as the start route for the customer's connection. Needs the `order:write` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `customer_id` | path | string (uuid) | Yes | The ID of the customer, as the create-customer route answered it. | | `setup_id` | path | string | Yes | The ID of the setup, as the start route answered it. | Responses: - `200` Successful Response: `PaymentMethodOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### POST /meals/v1/order/create/document Place an order. Places a meal order for a customer who approved the connection, to be delivered to an address on a delivery date. The customer pays with their own card, so the answer carries what your page needs to take the payment: - Confirm the payment on your page with Stripe.js, using `stripe_publishable_key` and `stripe_payment_intent.stripe_payment_intent_client_secret`. - The order is paid when `order_financial_status` is `paid` or the `order.paid` event arrives. Do not treat the order as paid when your page says the card was accepted. - An order that costs nothing is paid at once and `stripe_payment_intent` is `null`. The order carries its own field names: the three statuses `order_financial_status`, `order_fulfillment_status` and `order_delivery_status`, the amounts in cents, the vendor as it was when the order was placed, and the `line_items`. Your own `reference` and `metadata` come back as you sent them. Before anything is placed, the order is checked against the catalog, the vendor first: a vendor that does not exist, is not live, is archived or is not enabled for your company answers `404 not_found`. Then each failure answers `422` with its own code and nothing is created: - `delivery_not_available`: the vendor does not deliver to the address, or not on that date (a weekday it does not deliver on, a blackout date, a date with no menu, or a date whose order cutoff has passed). - `product_not_available`: a product is not offered on that date, is not live, or cannot be ordered. - `order_limits_not_met`: the order is below or above the vendor's limits on items or value. - `vendor_not_allowed_for_customer`: the customer's account is limited to certain vendors and this is not one of them; offer another vendor. The delivery address, the contact email address, the contact phone number and the notes are checked against the limits the order system holds them to (the fields say which). A value that fails answers `422 validation_error` naming the field. If the order system still refuses one of them, the answer is `422 validation_error` too, with a fixed message and no field. Other answers: `404 not_found` for an unknown customer, or for a vendor that cannot be used (see above); `409 connection_not_active` while the customer has not approved the connection or after they revoked it; `409 order_conflict` when the order cannot be placed in its current state. `order_limits_not_met` says which limit the order breaks; the vendor's limits are on the vendor. The order holds only the items you send. If the customer already started a cart for the same vendor, address zone and date in the Nurish'd app, that cart is emptied first, including any discount code or points on it. Sending the same `reference` again returns the order already placed instead of placing a second one. The reference, `metadata` and the key that placed the order are kept with the order. Needs the `order:write` scope. Request body: `OrderCreateInput` Responses: - `201` Successful Response: `OrderOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/order/query/documents List the orders you placed. Returns a page of the orders your company placed, newest first, without their line items; read one order to get them. Orders of a customer whose connection is no longer active are left out. Query parameters: - customer: Keep only the orders of this customer. - vendor: Keep only the orders of this vendor. - status: Keep only orders in this stage: `pending`, `paid`, `fulfilled` or `canceled`. This is the stage this API records for the order, not one of the statuses an order carries (`order_financial_status`, `order_fulfillment_status`, `order_delivery_status`). The stage is updated when an order is read or when a change is reported, so a list filter can lag behind until then. - from: Keep only orders placed at or after this time (ISO 8601). - to: Keep only orders placed at or before this time (ISO 8601). - page: The page number, from 1. - size: The page size, at most 50. Needs the `order:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `customer` | query | string (uuid) | No | Keep only the orders of this customer. | | `vendor` | query | string | No | Keep only the orders of this vendor. | | `status` | query | OrderStageEnum | No | Keep only orders in this stage: `pending`, `paid`, `fulfilled` or `canceled`. It is the stage this API records for the order, not an order status. | | `from` | query | string (date-time) | No | Keep only orders placed at or after this time. | | `to` | query | string (date-time) | No | Keep only orders placed at or before this time. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `OrderPageOutput` - `400` The request cannot be processed as sent, for example a range that ends before it starts.: `Error` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/order/{order_id}/get/document Get an order. Returns one order your company placed, with its `line_items`. While the payment is `pending` the answer carries the Stripe payment again, so a page can take the payment after a reload: confirm it with Stripe.js using `stripe_publishable_key` and `stripe_payment_intent.stripe_payment_intent_client_secret`. The order is paid when `order_financial_status` is `paid` or the `order.paid` event arrives. Answers `404` for an order that does not exist or belongs to another company or mode, and `409 connection_not_active` once the customer revoked the connection: you can no longer read their orders. Needs the `order:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `order_id` | path | string | Yes | The ID of the order, as `create` answered it. | Responses: - `200` Successful Response: `OrderOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `409` The request conflicts with the current state, for example a time slot that is already taken.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/vendor/query/documents List vendors. Returns a page of the vendors you can order from. Vendors that are not live yet or that were retired are never listed. The list leaves out the long description, the timezone, the address and the support contact of each vendor; read one vendor to get them. Query parameters: - name: Keep only vendors whose name contains this text. Not case sensitive. - page: The page number, from 1. - size: The page size, at most 50. Needs the `catalog:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `name` | query | string | No | Keep only vendors whose name contains this text. Not case sensitive. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `VendorPageOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/vendor/{vendor_id}/get/document Get a vendor. Returns one vendor with its full description, timezone, address and support contact. Answers `404` when the vendor does not exist, is not live yet or was retired. Needs the `catalog:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `vendor_id` | path | string | Yes | The ID of the vendor. | Responses: - `200` Successful Response: `VendorOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/vendor/{vendor_id}/menu/query/documents List the menus of a vendor. Returns a page of the menus of one vendor. A menu that is still being prepared or that was retired is never listed. The list leaves out the description of each menu; read one menu to get it. Query parameters: - status: Keep only menus in this status: `in_production`, `upcoming`, `expired` or `not_in_production`. - page: The page number, from 1. - size: The page size, at most 50. Needs the `catalog:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `vendor_id` | path | string | Yes | The ID of the vendor. | | `status` | query | MenuStatusEnum | No | Keep only menus in this status: `in_production`, `upcoming`, `expired` or `not_in_production`. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `MenuPageOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/vendor/{vendor_id}/menu/{menu_id}/get/document Get a menu. Returns one menu of a vendor with the IDs of its products for each meal slot: breakfast, lunch, dinner, snacks, supplements, drinks and misc. Answers `404` when the menu does not exist, is still being prepared or was retired. Needs the `catalog:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `vendor_id` | path | string | Yes | The ID of the vendor. | | `menu_id` | path | string | Yes | The ID of the menu. | Responses: - `200` Successful Response: `MenuOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/vendor/{vendor_id}/product/query/documents List the products of a vendor. Returns a page of the products of one vendor that you can order. Products that are not live yet or that were retired are never listed. The list leaves out the description and the features of each product, and its creation and update times; read one product to get them. Query parameters: - name: Keep only products whose name contains this text. Not case sensitive. - type: Keep only products of this type: `Meal`, `Bulk` or `Misc`. - collection: Keep only products of this collection: `Breakfast`, `Lunch`, `Dinner`, `Drink`, `Snack`, `Supplement` or `Sauce`. - tag: Keep only products with this tag, given as the tag ID. - page: The page number, from 1. - size: The page size, at most 50. Needs the `catalog:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `vendor_id` | path | string | Yes | The ID of the vendor. | | `name` | query | string | No | Keep only products whose name contains this text. Not case sensitive. | | `type` | query | ProductTypeEnum | No | Keep only products of this type: `Meal`, `Bulk` or `Misc`. | | `collection` | query | ProductCollectionEnum | No | Keep only products of this collection, for example `Breakfast` or `Snack`. | | `tag` | query | string | No | Keep only products with this tag, given as the tag ID. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `ProductPageOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/vendor/{vendor_id}/product/{product_id}/get/document Get a product. Returns one product of a vendor with its description and features. Answers `404` when the product does not exist, is not live yet, was retired, or is not something you can order as it is. Needs the `catalog:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `vendor_id` | path | string | Yes | The ID of the vendor. | | `product_id` | path | string | Yes | The ID of the product. | Responses: - `200` Successful Response: `ProductOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documents List the delivery dates of a zone. Returns `valid_delivery_dates`: the dates a delivery zone can deliver on between two dates, oldest first. Each date is the instant of midnight at the start of the delivery day in the timezone of the vendor (`vendor_timezone` on the vendor, an IANA name such as `America/Toronto`), written in UTC: for a vendor in Eastern time, the delivery day 2026-11-24 is listed as `2026-11-24T05:00:00Z`. The date part of each value is the delivery day, and that day, as `YYYY-MM-DD`, is what the date route and `order_delivery_date` take. A date is listed only when the zone delivers on that weekday, ordering for it is still open (its order cutoff has not passed), a menu is in production for it, and it is not a blackout date. Dates that can no longer be ordered are never listed, so a `from` in the past lists nothing before today, and a `from` in the future still lists every date from that day on that can be ordered. The two dates can be at most 60 days apart, and `to` at most 60 days from now. Answers `400` when `from` is after `to`, the range is longer than 60 days, or `to` is more than 60 days from now. Answers `404` when the vendor or the zone cannot be seen, which includes a vendor that is not live. Query parameters: - from: The first date to look at, as `YYYY-MM-DD`. Required. - to: The last date to look at, as `YYYY-MM-DD`. Required. Needs the `catalog:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `vendor_id` | path | string | Yes | The ID of the vendor. | | `zone_id` | path | string | Yes | The ID of the delivery zone. | | `from` | query | string (date) | Yes | The first date to look at, as `YYYY-MM-DD`. | | `to` | query | string (date) | Yes | The last date to look at, as `YYYY-MM-DD`. At most 60 days after `from` and at most 60 days from now. | Responses: - `200` Successful Response: `DeliveryDatesOutput` - `400` The request cannot be processed as sent, for example a range that ends before it starts.: `Error` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{date}/get/document Get what a zone offers on a delivery date. Returns what a delivery zone offers on one delivery day. The day is written `YYYY-MM-DD` in the path, which is the date part of a value of `valid_delivery_dates` (the full value with its time is not accepted here). The answer has when production starts, the delivery date, when ordering for it closes (`order_cutoff_date`), the ID of the menu in production for it (`menu`) and the IDs of the products you can order for it (`all_unique_product_ids`, the supplements of the menu included). Every product ID in the answer, in `all_unique_product_ids` and in `additional_product_ids`, is a product the product routes of this vendor answer: an ID of a product that is not live, is archived or cannot be ordered is left out. The vendor, the zone, the blackout date and the menu are answered as IDs. To read the answer: when `menu` is `null` and `all_unique_product_ids` is empty, the zone cannot deliver on the date. That is the case for a blackout date (`is_given_date_blackout` is `true`), for a date with no menu, and for a weekday the zone does not deliver on, which also has no `production_date`, `delivery_date` or `order_cutoff_date`. A date whose order cutoff has passed, which includes every date in the past, is answered the same way as a weekday the zone does not deliver on: nothing can be ordered for it. Answers `404` when the vendor or the zone cannot be seen, which includes a vendor that is not live. Needs the `catalog:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `vendor_id` | path | string | Yes | The ID of the vendor. | | `zone_id` | path | string | Yes | The ID of the delivery zone. | | `date` | path | string (date) | Yes | The delivery day, as `YYYY-MM-DD`: the date part of a value of `valid_delivery_dates`, for example `2026-11-24` for `2026-11-24T05:00:00Z`. A time of day is not accepted. | Responses: - `200` Successful Response: `DeliveryDateOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `404` The thing you asked for does not exist, or it belongs to another company or to the other mode.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error` ### GET /meals/v1/zone/query/documents Find the delivery zones that serve a place. Returns a page of the delivery zones that serve a city: the best matching zone of each vendor that delivers there. A zone can cover one city, one province or a whole country. Pass `vendor` to ask about one vendor: the page then holds that vendor's zone, and an empty page means the vendor does not deliver there. The place is compared exactly with what the zone holds: `city`, `state` and `country` must match letter for letter, and letter case counts (`Toronto` does not find a zone stored as `toronto`), so nothing is guessed or trimmed. Each vendor answers one zone at most: the one that fits the place best, which is a zone for the city, else a zone for the whole province, else a zone for the whole country. A vendor with a zone for another city of the province is not found. Query parameters: - city: The city to look up, exactly as the zone holds it. Required. - state: The two-letter province code, in capitals, for example `ON`. Required. - country: The two-letter country code, in capitals, for example `CA`. Required. - vendor: The ID of one vendor to look at. Optional. - page: The page number, from 1. - size: The page size, at most 50. Needs the `catalog:read` scope. | Name | In | Type | Required | Description | | --- | --- | --- | --- | --- | | `city` | query | string | Yes | The city to look up, exactly as the zone holds it: letter case counts. | | `state` | query | string | Yes | The two-letter province code, in capitals, for example `ON`. | | `country` | query | string | Yes | The two-letter country code, in capitals, for example `CA`. | | `vendor` | query | string | No | The ID of one vendor to look at. Without it, every vendor is looked at. | | `page` | query | integer | No | The page number, from 1. | | `size` | query | integer | No | The page size, at most 50. | Responses: - `200` Successful Response: `ZonePageOutput` - `401` The API key is missing, wrong, expired or revoked.: `Error` - `403` The key is not allowed to do this: a missing scope, a connection that is not active or a company that is not live.: `Error` - `422` The request is not valid. The message says which part.: `Error` - `429` Too many calls. Wait the number of seconds in the `Retry-After` header.: `Error` - `500` Something went wrong on our side. Try again later and quote the `request_id`.: `Error` - `502` A Nurish'd service this call depends on could not complete it. Try again later.: `Error` - `503` A Nurish'd service this call depends on is unavailable. Try again later.: `Error` - `504` A Nurish'd service this call depends on did not answer in time. Try again.: `Error`