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. Your project has the
nurishdclient file and a Sandbox key inNURISHD_API_KEY. - Your key has the scope
catalog:read. Every call in this tutorial needs it. Runcheck_keyfrom 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.
GET /meals/v1/zone/query/documentsfinds 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.GET /meals/v1/vendor/{vendor_id}/get/documentgives the name of the vendor and its minimum order.GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documentslists the dates the zone delivers on.GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{date}/get/documentsays which products you can order for one date. It gives product ids only.GET /meals/v1/vendor/{vendor_id}/product/query/documentslists 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.
def money(cents, currency):
return f"{cents / 100:.2f} {currency}"function money(cents, currency) {
return `${(cents / 100).toFixed(2)} ${currency}`;
}function money(cents: number, currency: string): string {
return `${(cents / 100).toFixed(2)} ${currency}`;
} 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.
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)}")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 printVendor(vendorId: string, currency: string) {
const vendor = await call<Vendor>(
'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)}`);
}
} 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.
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"]]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 deliveryDays(zonePath: string): Promise<string[]> {
const today = new Date();
const inTwoWeeks = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000);
const answer = await call<DeliveryDates>(
'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));
} static List<String> 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<String> 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.
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)}")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 printMeals(
vendorId: string,
zonePath: string,
day: string,
currency: string,
) {
const offer = await call<DayOffer>(
'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<Product>(
`/meals/v1/vendor/${vendorId}/product/query/documents`,
)) {
if (offered.has(product.product_id)) {
console.log(
` ${product.product_name}: ${money(product.product_price, currency)}`,
);
}
}
} 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<String> 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.
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)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 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);
} 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<String> 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.
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}.")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}.`);
}
}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<Zone>('/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}.`);
}
} 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<JsonNode> 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.
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 CADYour 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.
The whole program#
# 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)// 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);
}// 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<Vendor>(
'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<string[]> {
const today = new Date();
const inTwoWeeks = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000);
const answer = await call<DeliveryDates>(
'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<DayOffer>(
'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<Product>(
`/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<Zone>('/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);
}// 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<String> 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<String> 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<String> 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<String> 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<JsonNode> 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 <date> | 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: menus, products and delivery dates in full.
- Pagination: lists and filters.
- Connect a customer from your own sign-in: link a customer to your company.
- Place a meal order: order the meals you found.
Something wrong on this page? Email hello@nurishd.io with the page address.