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. 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#
mkdir nurishd-tutorial
cd nurishd-tutorial
python -m venv .venvTurn 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.
pip install requestsOn some systems the commands are python3 and pip3. Use those if python is not found.
JavaScript#
mkdir nurishd-tutorial
cd nurishd-tutorial
npm init -y
npm pkg set type=moduletype=module lets you write import in .js files. You install no packages. Node has fetch built in.
TypeScript#
mkdir nurishd-tutorial
cd nurishd-tutorial
npm init -y
npm pkg set type=module
npm install --save-dev typescript @types/nodeTypeScript checks your types. @types/node teaches it about Node. Save this as tsconfig.json in the project folder:
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"skipLibCheck": true,
"types": ["node"]
}
}Java#
Create the folders:
mkdir -p nurishd-tutorial/src/main/java/tutorial
cd nurishd-tutorialOn 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 version="1.0" encoding="UTF-8"?>
<!-- file: pom.xml -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>nurishd-tutorial</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.4.1</version>
</plugin>
</plugins>
</build>
</project>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:
export NURISHD_API_KEY="nk-test-your-key-here"Windows 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.
# 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// 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;
}
}// 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<string, string | number | boolean | string[]>;
/** One page of a list. */
export interface Page<T> {
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<T>(
method: Method,
path: string,
options: { params?: Params; body?: unknown } = {},
): Promise<T> {
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<T>(
path: string,
params: Params = {},
): AsyncGenerator<T> {
for (let page = 1; ; page++) {
const answer = await call<Page<T>>('GET', path, {
params: { ...params, page },
});
yield* answer.data;
if (!answer.has_next) return;
}
}// 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<String, ?> params, Object body) {
if (API_KEY == null || API_KEY.isBlank()) {
throw new IllegalStateException("Set NURISHD_API_KEY first.");
}
try {
List<String> query = new ArrayList<>();
for (Map.Entry<String, ?> 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<String> 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<JsonNode> pages(String path, Map<String, ?> params) {
List<JsonNode> items = new ArrayList<>();
for (int page = 1; ; page++) {
Map<String, Object> 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 theX-Partner-API-Keyheader. If the answer is429 rate_limited, it waits the number of seconds in theRetry-Afterheader and tries once more. See Rate limits.- When the API answers with an error,
callraises an error object instead of returning. The object has the HTTPstatus, thecodeand the request id. Branch oncode, not on the message. See 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.
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 asparams. - A JSON body is data you send with a
POSTorPUTcall. You pass it asbody.
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.
# 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)// 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);
}// 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<Key>('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<Vendor>('/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);
}// 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<String> 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, ornpx tsx check_key.tson Node older than 22.18. To check the types only, runnpx 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.
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_14344b708031767a78e80b11a162dcbeWhat each line means:
keyis the name you gave the key in the console.mode: testmeans the key belongs to the Sandbox. Everything you do with it uses fake data. A Production key printsmode: prod. See Environments.scopeslists what this key may do. A call that needs a scope the key lacks fails with403 scope_not_granted. See Scopes.- Each
vendorline is one vendor. You asked for two per page, andpageskept reading until none were left. refusedis the error you caused on purpose.422 validation_errormeans something you sent broke a rule. Here it was the page size. Keep the request id when you ask support for help.
The whole program#
The files above are the whole program. Your project now holds these files.
- Python:
nurishd.pyandcheck_key.py - JavaScript:
package.json,nurishd.jsandcheck_key.js - TypeScript:
package.json,tsconfig.json,nurishd.tsandcheck_key.ts - Java:
pom.xml,src/main/java/tutorial/Nurishd.javaandsrc/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: link a customer to your company so you can order for them.
- Show meals for an address: find the vendors and meals that deliver to an address.
- Place a meal order: order meals for a connected customer and take the payment.
- Receive order webhooks: build a server that Nurish'd calls when an order changes.
- Show dietitians: list the dietitians and their open times.
- Book a dietitian visit: book a visit for a patient.
- Read visit reports: read the report after a visit.
- Use Nurish'd with Shopify: connect a Shopify store to Nurish'd.
Something wrong on this page? Email hello@nurishd.io with the page address.