GET /api/v1/states, then quotes an order with POST /api/v1/orders/validate. Nothing is created, reserved or charged.
The Next.js, FastAPI, Laravel and Spring forms are a route of your server, so your storefront shows delivery prices without the key. Every visitor shares your key’s per-minute budget with your orders, so the routes keep the towns in memory (no longer than a day) and call validate only for a real cart. Rate-limit each visitor with your app’s own limits. The routes return the customer’s figures, never the quote’s reward.
Prerequisites
MART_API_KEY: your API key, withcatalog:readandorders:write.MART_API_BASE:https://sandbox.mart.pswhile you build,https://mart.pswhen you go live.MART_PRODUCT_ID: a product your key is offered.MART_STATE_ID: a town’sstates[].id, never a city’sid.
jq; Node 22.18 or later, which runs the .ts file as it is; Python 3.9 or later with httpx; PHP 7.4 or later with its curl extension; Go 1.22 or later; or Java 17 or later with Jackson (jackson-databind). Each file reads its variables from the environment and sets a timeout on every call. Run it on your own server: a browser or an app never holds the key.
Run the recipe
#!/usr/bin/env bash
# Show what delivery costs to one town, then quote an order without placing it.
# Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
set -euo pipefail
export LC_NUMERIC=C # printf reads and writes amounts with a decimal point
# api METHOD PATH [JSON]: sets $body, or prints the status and error code and stops.
api() {
local response status retry_after
response=$(curl --silent --show-error --max-time 30 --request "$1" \
--header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") --header 'Content-Type: application/json' \
${3:+--data "$3"} --write-out '\n%{http_code} %header{retry-after}' "$MART_API_BASE$2") || { echo "error: no answer" >&2; exit 1; }
read -r status retry_after <<<"${response##*$'\n'}"
body=${response%$'\n'*}
if [ "$status" -ge 300 ]; then
echo "error: $status $(jq -r '.error.code' <<<"$body" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}" >&2
exit 1
fi
}
# 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
# The towns and their fees change rarely: a storefront keeps this answer and reads it again
# on its own schedule, never once per visitor.
api GET /api/v1/states
fees=$(jq -c --argjson state "$MART_STATE_ID" '[.data.cities[].states[] | select(.id == $state)] | first | .delivery.fees' <<<"$body")
if [ "$fees" = null ]; then
echo "error: state $MART_STATE_ID is not a delivery town" >&2
exit 1
fi
echo "delivery fees for state $MART_STATE_ID:"
jq -r '.[] | "\(.from_total) \(.to_total) \(.fee)"' <<<"$fees" |
while read -r from to fee; do
if [ "$to" != null ]; then
printf ' from %.2f, less than %.2f: %.2f\n' "$from" "$to" "$fee"
else
printf ' from %.2f: %.2f\n' "$from" "$fee"
fi
done
# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
# reserved, but it counts against the same per-minute budget as creating orders.
order=$(jq -n --arg ref "quote-$(date +%s)" --argjson product "$MART_PRODUCT_ID" --argjson state "$MART_STATE_ID" '{
partner_reference: $ref,
payment_type: "cod",
products: [{product_id: $product, quantity: 1}],
shipping_address: {customer_name: "Test Buyer", phone: "0599000000", state_id: $state, address: "Main street 1"}
}')
api POST /api/v1/orders/validate "$order"
jq -r '"valid: \(.data.validation.valid)"' <<<"$body"
read -r products fee total < <(jq -r '.data.validation.quote | "\(.products_total) \(.shipping_fee) \(.order_total)"' <<<"$body")
printf 'products total: %.2f\ndelivery fee: %.2f\norder total: %.2f\n' "$products" "$fee" "$total"
// Show what delivery costs to one town, then quote an order without placing it.
// Node 22.18 or later runs this .ts file as it is.
// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
if (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');
const productId = Number(process.env.MART_PRODUCT_ID);
const stateId = Number(process.env.MART_STATE_ID);
async function api(method: string, path: string, payload?: unknown): Promise<any> {
const response = await fetch(`${base}${path}`, {
method,
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
body: payload === undefined ? undefined : JSON.stringify(payload),
signal: AbortSignal.timeout(30_000),
});
const body = await response.json().catch(() => null); // an edge error page is not JSON
if (!response.ok || body === null) {
const retryAfter = response.headers.get('retry-after');
console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);
process.exit(1);
}
return body;
}
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
const states = await api('GET', '/api/v1/states');
const town = states.data.cities.flatMap((city: any) => city.states).find((state: any) => state.id === stateId);
if (!town) {
console.error(`error: state ${stateId} is not a delivery town`);
process.exit(1);
}
console.log(`delivery fees for state ${stateId}:`);
for (const bracket of town.delivery.fees) {
const upper = bracket.to_total === null ? '' : `, less than ${bracket.to_total.toFixed(2)}`;
console.log(` from ${bracket.from_total.toFixed(2)}${upper}: ${bracket.fee.toFixed(2)}`);
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
const result = await api('POST', '/api/v1/orders/validate', {
partner_reference: `quote-${Date.now()}`,
payment_type: 'cod',
products: [{ product_id: productId, quantity: 1 }],
shipping_address: { customer_name: 'Test Buyer', phone: '0599000000', state_id: stateId, address: 'Main street 1' },
});
const quote = result.data.validation.quote;
console.log(`valid: ${result.data.validation.valid}`);
console.log(`products total: ${quote.products_total.toFixed(2)}`);
console.log(`delivery fee: ${quote.shipping_fee.toFixed(2)}`);
console.log(`order total: ${quote.order_total.toFixed(2)}`);
"""Show what delivery costs to one town, then quote an order without placing it. Python 3.9+, httpx.
Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
"""
import os
import sys
import time
import httpx
TIMEOUT = 30
client = httpx.Client(
base_url=os.environ["MART_API_BASE"],
headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
timeout=TIMEOUT,
)
product_id = int(os.environ["MART_PRODUCT_ID"])
state_id = int(os.environ["MART_STATE_ID"])
def body_of(response: httpx.Response):
"""The JSON body, or None for an answer that is not JSON (an edge error page)."""
try:
return response.json()
except ValueError:
return None
def check(response: httpx.Response) -> dict:
body = body_of(response)
if response.is_error or body is None:
code = body["error"]["code"] if body else "(not JSON)"
retry_after = response.headers.get("Retry-After")
sys.exit(f"error: {response.status_code} {code}" + (f", try again after {retry_after} s" if retry_after else ""))
return body
# 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
# The towns and their fees change rarely: a storefront keeps this answer and reads it again
# on its own schedule, never once per visitor.
cities = check(client.get("/api/v1/states"))["data"]["cities"]
town = next((state for city in cities for state in city["states"] if state["id"] == state_id), None)
if town is None:
sys.exit(f"error: state {state_id} is not a delivery town")
print(f"delivery fees for state {state_id}:")
for bracket in town["delivery"]["fees"]:
upper = "" if bracket["to_total"] is None else f", less than {bracket['to_total']:.2f}"
print(f" from {bracket['from_total']:.2f}{upper}: {bracket['fee']:.2f}")
# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
# reserved, but it counts against the same per-minute budget as creating orders.
result = check(client.post("/api/v1/orders/validate", json={
"partner_reference": f"quote-{int(time.time())}",
"payment_type": "cod",
"products": [{"product_id": product_id, "quantity": 1}],
"shipping_address": {"customer_name": "Test Buyer", "phone": "0599000000", "state_id": state_id, "address": "Main street 1"},
}))["data"]["validation"]
print(f"valid: {str(result['valid']).lower()}")
print(f"products total: {result['quote']['products_total']:.2f}")
print(f"delivery fee: {result['quote']['shipping_fee']:.2f}")
print(f"order total: {result['quote']['order_total']:.2f}")
<?php
// Show what delivery costs to one town, then quote an order without placing it. PHP 7.4 or later,
// with the curl extension. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID.
$base = getenv('MART_API_BASE');
$key = getenv('MART_API_KEY');
$productId = (int) getenv('MART_PRODUCT_ID');
$stateId = (int) getenv('MART_STATE_ID');
/**
* One request with the curl extension. Returns [status, headers (lower-case name => value), body];
* status 0 when there was no answer at all.
*/
function request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array
{
$headers = [];
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => ["Authorization: Bearer $key", 'Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
$parts = explode(':', $line, 2);
if (count($parts) === 2) {
$headers[strtolower(trim($parts[0]))] = trim($parts[1]);
}
return strlen($line);
},
]);
if ($payload !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
}
$body = curl_exec($curl);
$status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
return [$status, $headers, (string) $body];
}
/** A GET that must succeed: the decoded body, or the status and error code, and stop. */
function get(string $url, string $key): array
{
[$status, $headers, $raw] = request('GET', $url, $key);
$body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)
if ($status < 200 || $status >= 300 || !is_array($body)) {
$code = $status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)');
$wait = isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
fwrite(STDERR, "error: $code$wait\n");
exit(1);
}
return $body;
}
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
$states = get("$base/api/v1/states", $key);
$town = null;
foreach ($states['data']['cities'] as $city) {
foreach ($city['states'] as $state) {
if ($state['id'] === $stateId) {
$town = $state;
}
}
}
if ($town === null) {
fwrite(STDERR, "error: state $stateId is not a delivery town\n");
exit(1);
}
echo "delivery fees for state $stateId:\n";
foreach ($town['delivery']['fees'] as $bracket) {
$upper = $bracket['to_total'] === null ? '' : sprintf(', less than %.2f', $bracket['to_total']);
printf(" from %.2f%s: %.2f\n", $bracket['from_total'], $upper, $bracket['fee']);
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
[$status, $headers, $raw] = request('POST', "$base/api/v1/orders/validate", $key, json_encode([
'partner_reference' => 'quote-' . time(),
'payment_type' => 'cod',
'products' => [['product_id' => $productId, 'quantity' => 1]],
'shipping_address' => ['customer_name' => 'Test Buyer', 'phone' => '0599000000', 'state_id' => $stateId, 'address' => 'Main street 1'],
]));
$result = json_decode($raw, true);
if ($status !== 200 || !is_array($result)) {
$wait = isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($result['error']['code'] ?? '(not JSON)')) . "$wait\n");
exit(1);
}
$validation = $result['data']['validation'];
echo 'valid: ' . ($validation['valid'] ? 'true' : 'false') . "\n";
printf("products total: %.2f\n", $validation['quote']['products_total']);
printf("delivery fee: %.2f\n", $validation['quote']['shipping_fee']);
printf("order total: %.2f\n", $validation['quote']['order_total']);
//go:build ignore
// Show what delivery costs to one town, then quote an order without placing it. Go 1.22 or later.
// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
// Run it with: go run delivery-prices-and-quote.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)
var client = &http.Client{Timeout: 30 * time.Second}
func main() {
productID, _ := strconv.Atoi(os.Getenv("MART_PRODUCT_ID"))
stateID, _ := strconv.Atoi(os.Getenv("MART_STATE_ID"))
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
var tree struct {
Data struct {
Cities []struct {
States []struct {
ID int `json:"id"`
Delivery struct {
Fees []struct {
From float64 `json:"from_total"`
To *float64 `json:"to_total"` // null: no upper end
Fee float64 `json:"fee"`
} `json:"fees"`
} `json:"delivery"`
} `json:"states"`
} `json:"cities"`
} `json:"data"`
}
get("/api/v1/states", &tree)
found := false
for _, city := range tree.Data.Cities {
for _, state := range city.States {
if state.ID != stateID {
continue
}
found = true
fmt.Printf("delivery fees for state %d:\n", stateID)
for _, b := range state.Delivery.Fees {
if b.To != nil {
fmt.Printf(" from %.2f, less than %.2f: %.2f\n", b.From, *b.To, b.Fee)
} else {
fmt.Printf(" from %.2f: %.2f\n", b.From, b.Fee)
}
}
}
}
if !found {
fail(fmt.Errorf("state %d is not a delivery town", stateID))
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
order, err := json.Marshal(map[string]any{
"partner_reference": fmt.Sprintf("quote-%d", time.Now().Unix()),
"payment_type": "cod",
"products": []map[string]any{{"product_id": productID, "quantity": 1}},
"shipping_address": map[string]any{
"customer_name": "Test Buyer", "phone": "0599000000", "state_id": stateID, "address": "Main street 1",
},
})
if err != nil {
fail(err)
}
req, err := http.NewRequest(http.MethodPost, os.Getenv("MART_API_BASE")+"/api/v1/orders/validate", bytes.NewReader(order))
if err != nil {
fail(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fail(fmt.Errorf("no answer: %v", err))
}
var result struct {
Data struct {
Validation struct {
Valid bool `json:"valid"`
Quote struct {
ProductsTotal float64 `json:"products_total"`
ShippingFee float64 `json:"shipping_fee"`
OrderTotal float64 `json:"order_total"`
} `json:"quote"`
} `json:"validation"`
} `json:"data"`
}
decode(resp, &result)
v := result.Data.Validation
fmt.Println("valid:", v.Valid)
fmt.Printf("products total: %.2f\ndelivery fee: %.2f\norder total: %.2f\n",
v.Quote.ProductsTotal, v.Quote.ShippingFee, v.Quote.OrderTotal)
}
// get sends one GET and decodes its answer into out.
func get(path string, out any) {
req, err := http.NewRequest(http.MethodGet, os.Getenv("MART_API_BASE")+path, nil)
if err != nil {
fail(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
resp, err := client.Do(req)
if err != nil {
fail(fmt.Errorf("no answer: %v", err))
}
decode(resp, out)
}
// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),
// stops with its status and error code.
func decode(resp *http.Response, out any) {
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
fail(err)
}
var envelope struct {
Error *struct {
Code string `json:"code"`
} `json:"error"`
}
if resp.StatusCode >= 300 {
code := "(not JSON)"
if json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {
code = envelope.Error.Code
}
wait := ""
if after := resp.Header.Get("Retry-After"); after != "" {
wait = ", try again after " + after + " s"
}
fail(fmt.Errorf("%d %s%s", resp.StatusCode, code, wait))
}
if err := json.Unmarshal(raw, out); err != nil {
fail(fmt.Errorf("%d (not JSON)", resp.StatusCode))
}
}
func fail(err error) {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
// Show what delivery costs to one town, then quote an order without placing it. Java 17 or later, with Jackson.
// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
// Run it as a single file: java -cp <the Jackson jars> delivery-prices-and-quote.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
class DeliveryPricesAndQuote {
static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
int productId = Integer.parseInt(System.getenv("MART_PRODUCT_ID"));
int stateId = Integer.parseInt(System.getenv("MART_STATE_ID"));
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
JsonNode town = null;
for (JsonNode city : get("/api/v1/states").path("data").path("cities")) {
for (JsonNode state : city.path("states")) {
if (state.path("id").asInt() == stateId) {
town = state;
}
}
}
if (town == null) {
fail("state " + stateId + " is not a delivery town");
}
System.out.println("delivery fees for state " + stateId + ":");
for (JsonNode bracket : town.path("delivery").path("fees")) {
String upper = bracket.path("to_total").isNull() ? ""
: String.format(Locale.ROOT, ", less than %.2f", bracket.path("to_total").asDouble());
System.out.printf(Locale.ROOT, " from %.2f%s: %.2f%n", bracket.path("from_total").asDouble(), upper,
bracket.path("fee").asDouble());
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
String order = JSON.writeValueAsString(Map.of(
"partner_reference", "quote-" + System.currentTimeMillis(),
"payment_type", "cod",
"products", List.of(Map.of("product_id", productId, "quantity", 1)),
"shipping_address", Map.of("customer_name", "Test Buyer", "phone", "0599000000",
"state_id", stateId, "address", "Main street 1")));
HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + "/api/v1/orders/validate"))
.header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(30))
.POST(HttpRequest.BodyPublishers.ofString(order))
.build();
HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
JsonNode result = parse(response.body());
if (response.statusCode() >= 300 || result == null) {
fail(response.statusCode() + " " + code(result) + when(response));
}
JsonNode validation = result.path("data").path("validation");
JsonNode quote = validation.path("quote");
System.out.println("valid: " + validation.path("valid").asBoolean());
System.out.printf(Locale.ROOT, "products total: %.2f%n", quote.path("products_total").asDouble());
System.out.printf(Locale.ROOT, "delivery fee: %.2f%n", quote.path("shipping_fee").asDouble());
System.out.printf(Locale.ROOT, "order total: %.2f%n", quote.path("order_total").asDouble());
}
/** One GET that must succeed: the decoded body, or the status and error code, and stop. */
static JsonNode get(String path) throws InterruptedException {
HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + path))
.header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
.timeout(Duration.ofSeconds(30))
.GET()
.build();
HttpResponse<String> response;
try {
response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
fail("no answer: " + e.getMessage());
return null;
}
JsonNode body = parse(response.body());
if (response.statusCode() >= 300 || body == null) {
fail(response.statusCode() + " " + code(body) + when(response));
}
return body;
}
/** The JSON body, or null for an answer that is not JSON (an edge error page). */
static JsonNode parse(String text) {
try {
return JSON.readTree(text);
} catch (IOException e) {
return null;
}
}
static void fail(String message) {
System.err.println("error: " + message);
System.exit(1);
}
static String code(JsonNode body) {
return body == null ? "(not JSON)" : body.path("error").path("code").asText();
}
/** ", try again after N s" when the answer says how long to wait (Retry-After), else nothing. */
static String when(HttpResponse<String> response) {
return response.headers().firstValue("Retry-After").map(s -> ", try again after " + s + " s").orElse("");
}
}
// app/api/delivery-quote/route.ts: what delivery costs to a town, and, for a real cart only, the
// order's totals. Your storefront calls your server, and your server calls Mart, so the key never
// reaches a browser. POST {"state_id": 45} for the fees, plus "products": [{"product_id": 123,
// "quantity": 1}] for a quote. Needs MART_API_BASE and MART_API_KEY in the server's environment.
//
// Every visitor shares your key's per-minute budget with your order creation, so this route asks
// Mart as little as it can: the towns are kept in memory, and validate runs only for a real cart.
// Limit how often one visitor may call it, with your app's own rate limiting.
import { NextResponse } from 'next/server';
const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
// How long to keep the towns and fees: your choice. Mart's guide re-reads GET /states at least
// daily for its prices, so keep it no longer than a day.
const TOWNS_CACHE_MS = Number(process.env.TOWNS_CACHE_SECONDS ?? 86_400) * 1000;
let towns: { until: number; list: any[] } | null = null;
async function mart(method: string, path: string, payload?: unknown): Promise<{ status: number; body: any }> {
const response = await fetch(`${base}${path}`, {
method,
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
body: payload === undefined ? undefined : JSON.stringify(payload),
signal: AbortSignal.timeout(30_000),
cache: 'no-store',
});
return { status: response.status, body: await response.json().catch(() => null) };
}
export async function POST(request: Request) {
const input = await request.json().catch(() => ({}));
const stateId = Number(input.state_id);
if (!Number.isInteger(stateId)) {
return NextResponse.json({ error: 'state_id is required' }, { status: 422 });
}
// The town's fee brackets: a products total of at least from_total and less than to_total pays fee.
if (towns === null || towns.until < Date.now()) {
const states = await mart('GET', '/api/v1/states');
if (states.status >= 300 || states.body === null) {
return NextResponse.json({ error: 'delivery prices are unavailable' }, { status: 502 });
}
towns = { until: Date.now() + TOWNS_CACHE_MS, list: states.body.data.cities.flatMap((city: any) => city.states) };
}
const town = towns.list.find((state: any) => state.id === stateId);
if (!town) {
return NextResponse.json({ error: 'unknown_town' }, { status: 422 });
}
if (!Array.isArray(input.products) || input.products.length === 0) {
return NextResponse.json({ fees: town.delivery.fees });
}
// The quote, for a real cart only: the same body as a real order. Nothing is created or reserved.
const quote = await mart('POST', '/api/v1/orders/validate', {
partner_reference: `quote-${Date.now()}`,
payment_type: 'cod',
products: input.products.map((line: any) => ({ product_id: Number(line.product_id), quantity: Number(line.quantity ?? 1) })),
shipping_address: { customer_name: 'Quote', phone: '0599000000', state_id: stateId, address: 'Quote' },
});
if (quote.status >= 300 || quote.body === null) {
// 422 names what is wrong (error.code): an unknown product, no stock, an inactive town.
return NextResponse.json({ error: quote.body?.error?.code ?? 'unavailable' }, { status: quote.status === 422 ? 422 : 502 });
}
// The customer's figures only: the quote's reward is your money, never shown to a visitor.
const { products_total, shipping_fee, order_total } = quote.body.data.validation.quote;
return NextResponse.json({ fees: town.delivery.fees, quote: { products_total, shipping_fee, order_total } });
}
"""What delivery costs to a town, and, for a real cart only, the order's totals.
Your storefront calls your server, and your server calls Mart, so the key never reaches a browser.
POST /delivery-quote {"state_id": 45} for the fees, plus "products": [{"product_id": 123,
"quantity": 1}] for a quote. Run: uvicorn delivery_prices_and_quote:app
Needs MART_API_BASE and MART_API_KEY in the server's environment.
Every visitor shares your key's per-minute budget with your order creation, so this route asks Mart
as little as it can: the towns are kept in memory, and validate runs only for a real cart. Limit how
often one visitor may call it, with your app's own rate limiting.
"""
import os
import time
import httpx
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
mart = httpx.AsyncClient(
base_url=os.environ["MART_API_BASE"],
headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
timeout=30,
)
# How long to keep the towns and fees: your choice. Mart's guide re-reads GET /states at least
# daily for its prices, so keep it no longer than a day.
TOWNS_CACHE_SECONDS = int(os.environ.get("TOWNS_CACHE_SECONDS", 86_400))
towns: dict = {"until": 0.0, "list": []}
def json_of(response: httpx.Response) -> dict:
"""The JSON body, or a 502 for an answer that is not JSON (an edge error page)."""
try:
return response.json()
except ValueError:
raise HTTPException(502, "Mart answered with something that is not JSON")
class Line(BaseModel):
product_id: int
quantity: int = 1
class QuoteRequest(BaseModel):
state_id: int
products: list[Line] = []
@app.post("/delivery-quote")
async def delivery_quote(request: QuoteRequest) -> dict:
# The town's fee brackets: a products total of at least from_total and less than to_total pays fee.
if towns["until"] < time.monotonic():
states = await mart.get("/api/v1/states")
if states.is_error:
raise HTTPException(502, "delivery prices are unavailable")
towns["list"] = [state for city in json_of(states)["data"]["cities"] for state in city["states"]]
towns["until"] = time.monotonic() + TOWNS_CACHE_SECONDS
town = next((state for state in towns["list"] if state["id"] == request.state_id), None)
if town is None:
raise HTTPException(422, "unknown_town")
if not request.products:
return {"fees": town["delivery"]["fees"]}
# The quote, for a real cart only: the same body as a real order. Nothing is created or reserved.
quote = await mart.post("/api/v1/orders/validate", json={
"partner_reference": f"quote-{int(time.time())}",
"payment_type": "cod",
"products": [line.model_dump() for line in request.products],
"shipping_address": {"customer_name": "Quote", "phone": "0599000000", "state_id": request.state_id, "address": "Quote"},
})
if quote.is_error:
# 422 names what is wrong (error.code): an unknown product, no stock, an inactive town.
raise HTTPException(422 if quote.status_code == 422 else 502, "quote refused")
# The customer's figures only: the quote's reward is your money, never shown to a visitor.
figures = json_of(quote)["data"]["validation"]["quote"]
return {
"fees": town["delivery"]["fees"],
"quote": {name: figures[name] for name in ("products_total", "shipping_fee", "order_total")},
}
<?php
// app/Http/Controllers/MartDeliveryQuoteController.php: what delivery costs to a town, and, for a real
// cart only, the order's totals. Your storefront calls your server, and your server calls Mart, so the
// key never reaches a browser. POST {"state_id": 45} for the fees, plus "products": [{"product_id": 123,
// "quantity": 1}] for a quote.
// routes/api.php: Route::post('/mart/delivery-quote', MartDeliveryQuoteController::class)->middleware('throttle:...');
// config/services.php: 'mart' => ['base' => env('MART_API_BASE'), 'key' => env('MART_API_KEY'),
// 'towns_cache_seconds' => env('TOWNS_CACHE_SECONDS')],
//
// Every visitor shares your key's per-minute budget with your order creation, so this route asks
// Mart as little as it can: the towns are cached, and validate runs only for a real cart. Set the
// throttle middleware to how often one visitor may call it.
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
class MartDeliveryQuoteController extends Controller
{
public function __invoke(Request $request): JsonResponse
{
$input = $request->validate([
'state_id' => 'required|integer',
'products' => 'array',
'products.*.product_id' => 'required|integer',
'products.*.quantity' => 'integer|min:1',
]);
$mart = Http::withToken(config('services.mart.key'))->timeout(30)->baseUrl(config('services.mart.base'));
// The town's fee brackets: a products total of at least from_total and less than to_total pays fee.
// How long to keep them: your choice. Mart's guide re-reads GET /states at least daily for
// its prices, so keep them no longer than a day.
$towns = Cache::get('mart.towns');
if ($towns === null) {
$states = $mart->get('/api/v1/states');
if ($states->failed()) {
return response()->json(['error' => 'delivery prices are unavailable'], 502);
}
$towns = collect($states->json('data.cities'))->flatMap(fn (array $city) => $city['states'])->values()->all();
Cache::put('mart.towns', $towns, (int) (config('services.mart.towns_cache_seconds') ?: 86400));
}
$town = collect($towns)->firstWhere('id', (int) $input['state_id']);
if ($town === null) {
return response()->json(['error' => 'unknown_town'], 422);
}
if (empty($input['products'])) {
return response()->json(['fees' => $town['delivery']['fees']]);
}
// The quote, for a real cart only: the same body as a real order. Nothing is created or reserved.
$quote = $mart->post('/api/v1/orders/validate', [
'partner_reference' => 'quote-'.time(),
'payment_type' => 'cod',
'products' => array_map(fn (array $line) => ['product_id' => (int) $line['product_id'], 'quantity' => (int) ($line['quantity'] ?? 1)], $input['products']),
'shipping_address' => ['customer_name' => 'Quote', 'phone' => '0599000000', 'state_id' => (int) $input['state_id'], 'address' => 'Quote'],
]);
if ($quote->failed()) {
// 422 names what is wrong (error.code): an unknown product, no stock, an inactive town.
return response()->json(['error' => $quote->json('error.code')], $quote->status() === 422 ? 422 : 502);
}
// The customer's figures only: the quote's reward is your money, never shown to a visitor.
return response()->json([
'fees' => $town['delivery']['fees'],
'quote' => collect($quote->json('data.validation.quote'))->only(['products_total', 'shipping_fee', 'order_total']),
]);
}
}
package com.example.martrecipes;
import com.fasterxml.jackson.databind.JsonNode;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;
/**
* What delivery costs to a town, and, for a real cart only, the order's totals. Your storefront calls
* your server, and your server calls Mart, so the key never reaches a browser. POST /mart/delivery-quote
* {"state_id": 45} for the fees, plus "products": [{"product_id": 123, "quantity": 1}] for a quote.
*
* Every visitor shares your key's per-minute budget with your order creation, so this route asks Mart
* as little as it can: the towns are kept in memory, and validate runs only for a real cart. Limit how
* often one visitor may call it, with your app's own rate limiting.
*/
@RestController
public class DeliveryQuoteController {
record Line(Integer product_id, Integer quantity) {}
record QuoteRequest(Integer state_id, List<Line> products) {}
private final RestClient mart;
// How long to keep the towns and fees: your choice. Mart's guide re-reads GET /states at least
// daily for its prices, so keep it no longer than a day.
private final Duration townsCache;
private List<JsonNode> towns = List.of();
private Instant townsUntil = Instant.EPOCH;
// MART_API_BASE and MART_API_KEY come from the environment; every call has a timeout.
public DeliveryQuoteController(@Value("${MART_API_BASE}") String base, @Value("${MART_API_KEY}") String key,
@Value("${TOWNS_CACHE_SECONDS:86400}") long townsCacheSeconds) {
SimpleClientHttpRequestFactory timeouts = new SimpleClientHttpRequestFactory();
timeouts.setConnectTimeout(Duration.ofSeconds(10));
timeouts.setReadTimeout(Duration.ofSeconds(30));
this.mart = RestClient.builder()
.baseUrl(base)
.defaultHeader("Authorization", "Bearer " + key)
.requestFactory(timeouts)
.build();
this.townsCache = Duration.ofSeconds(townsCacheSeconds);
}
@PostMapping("/mart/delivery-quote")
public ResponseEntity<Object> quote(@RequestBody QuoteRequest input) {
if (input.state_id() == null) {
return ResponseEntity.status(422).body(Map.of("error", "state_id is required"));
}
// The town's fee brackets: a products total of at least from_total and less than to_total pays fee.
JsonNode town;
try {
town = findTown(input.state_id());
} catch (RestClientException e) {
return ResponseEntity.status(502).body(Map.of("error", "delivery prices are unavailable"));
}
if (town == null) {
return ResponseEntity.status(422).body(Map.of("error", "unknown_town"));
}
if (input.products() == null || input.products().isEmpty()) {
return ResponseEntity.ok(Map.of("fees", town.path("delivery").path("fees")));
}
// The quote, for a real cart only: the same body as a real order. Nothing is created or reserved.
List<Map<String, Integer>> lines = new ArrayList<>();
for (Line line : input.products()) {
if (line.product_id() == null) {
return ResponseEntity.status(422).body(Map.of("error", "product_id is required"));
}
lines.add(Map.of("product_id", line.product_id(), "quantity", line.quantity() == null ? 1 : line.quantity()));
}
Map<String, Object> order = Map.of(
"partner_reference", "quote-" + System.currentTimeMillis(),
"payment_type", "cod",
"products", lines,
"shipping_address", Map.of("customer_name", "Quote", "phone", "0599000000", "state_id", input.state_id(), "address", "Quote"));
ResponseEntity<JsonNode> quote;
try {
quote = mart.post().uri("/api/v1/orders/validate").body(order).retrieve()
.onStatus(HttpStatusCode::isError, (request, response) -> {})
.toEntity(JsonNode.class);
} catch (RestClientException e) {
return ResponseEntity.status(502).body(Map.of("error", "quote unavailable"));
}
if (quote.getStatusCode().isError() || quote.getBody() == null) {
// 422 names what is wrong (error.code): an unknown product, no stock, an inactive town.
return ResponseEntity.status(quote.getStatusCode().value() == 422 ? 422 : 502).body(Map.of("error", "quote refused"));
}
// The customer's figures only: the quote's reward is your money, never shown to a visitor.
JsonNode figures = quote.getBody().path("data").path("validation").path("quote");
return ResponseEntity.ok(Map.of("fees", town.path("delivery").path("fees"), "quote", Map.of(
"products_total", figures.path("products_total"),
"shipping_fee", figures.path("shipping_fee"),
"order_total", figures.path("order_total"))));
}
private synchronized JsonNode findTown(int stateId) {
if (Instant.now().isAfter(townsUntil)) {
JsonNode states = mart.get().uri("/api/v1/states").retrieve().body(JsonNode.class);
List<JsonNode> list = new ArrayList<>();
for (JsonNode city : states.path("data").path("cities")) {
city.path("states").forEach(list::add);
}
towns = list;
townsUntil = Instant.now().plus(townsCache);
}
for (JsonNode state : towns) {
if (state.path("id").asInt() == stateId) {
return state;
}
}
return null;
}
}
Verify the result
delivery fees for state 412:
from 0.00, less than <amount>: <fee>
from <amount>: <fee>
valid: true
products total: <amount>
delivery fee: <fee>
order total: <amount>
- A bracket applies when the products total is at least its first figure and less than the second. The brackets are your account’s own.
valid: truemeans an order with the same body would pass every check now. Stock, prices and fees can still move: the created order’s figures are the ones that count.
Troubleshooting
| What you see | What to do |
|---|---|
error: state … is not a delivery town or 422 invalid_state | Read GET /api/v1/states again and use an active states[].id. |
422 product_not_offered | Pick a product from GET /api/v1/products/ids. |
422 insufficient_stock | Lower the quantity or pick another product. |
422 orders_not_enabled | Ask Mart to enable orders for your key. |
| Any recipe | What to do |
|---|---|
401 missing_api_key or invalid_api_key | Check that MART_API_KEY holds the whole key. A key still refused needs a replacement from Mart. |
401 key_environment_mismatch | Point MART_API_BASE at the environment that issued the key. |
403 insufficient_scope | Ask Mart to add the scope in details.required_scope. |
429 rate_limit_exceeded | Wait the Retry-After the error line shows, then run it again. |
error: no answer, or a timeout | Check MART_API_BASE and your network. |
error: with (not JSON) | A proxy or firewall answered, not the API. Check MART_API_BASE and your network. |
