Developers

Search the docs

Search guides and headings.

Set up your project

Create a project in Python, JavaScript, TypeScript or Java that calls the Nurish'd Connect API with your Sandbox key.

View as Markdown

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.

LanguageYou need
PythonPython 3.10 or newer. Check with python --version.
JavaScriptNode 20 or newer. Check with node --version.
TypeScriptNode 20 or newer, and Node 22.18 or newer to run .ts files directly.
JavaJava 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#

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

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

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

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.
  • scopes lists what this key may do. A call that needs a scope the key lacks fails with 403 scope_not_granted. See 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 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 seeWhyWhat to do
401 invalid_api_keyThe 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_grantedThe 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 modulepackage.json has no "type": "module".Run npm pkg set type=module.
fetch is not definedYour Node is older than 18.Install Node 20 or newer.
ERR_UNKNOWN_FILE_EXTENSION for a .ts fileYour 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 recognizedMaven is not installed or not on your path.Install Maven, open a new terminal and run mvn --version.
release version 17 not supportedYour Java is older than 17.Install Java 17 or newer.

Next#

Pick the tutorial that matches what you build.