stage 2 of 6 · try of as-shipped

quote-options

right

Every Tern service for a cart, cheapest first (needs from the docs: D1 grams, D2 current endpoint)

Made
28 Nov 2026, 20:39 UTC
Model
claude-sonnet-5-5
Steps
5
Tool calls
3
Friction
1 flagged step
Tokens read
101k
Time
10s
Cost
$0.032
Address
tern-docs/try/20261128-2029-7znr/quote-options
1quote-at-checkoutright2quote-optionsright3book-shipmentright4sync-shipmentsright5order-statusright6cancel-before-pickupright
TranscriptPromptFilesOpen flagged steps
1
user
This is the backend of Larkspur Tea, a small online tea shop. We ship with Tern, a parcel carrier. Tern's API documentation is at http://loc…
This is the backend of Larkspur Tea, a small online tea shop. We ship with Tern, a parcel carrier. Tern's API documentation is at http://localhost:8080/ and Tern's sandbox API is running at http://localhost:8081 (the test key is already in `shop/settings.py`). Implement `quote_options` in `shop/shipping.py`: the customer picks a delivery speed at checkout, so we need every service Tern offers for the cart and postcode, with its price in pence and the days it takes, cheapest first. Keep the shop's existing tests passing; add your own if you like.
2
agent · Bash
cd /app; git ls-files; cat shop/shipping.py shop/settings.py; curl -s localhost:8080/
.gitignore
cd /app; git ls-files; cat shop/shipping.py shop/settings.py; curl -s localhost:8080/
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date

from shop.cart import Cart
from shop.orders import Order


def quote_at_checkout(cart: Cart, postcode: str) -> int:
    """The cheapest price Tern offers to ship this cart from the warehouse to postcode, in pence."""
    raise NotImplementedError


def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
    """Every service Tern offers for this cart and postcode, as (service, price in pence, days to deliver),
    cheapest first."""
    raise NotImplementedError


def book(order: Order, service: str) -> str:
    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    raise NotImplementedError


def shipments_since(day: date) -> list[dict]:
    """Every Tern shipment created on or after day, as Tern describes them."""
    raise NotImplementedError


def order_status(shipment_id: str) -> str:
    """The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
    raise NotImplementedError


def cancel(order: Order) -> bool:
    """Cancel the order's Tern shipment. True if Tern cancelled it; False if it is too late to cancel."""
    raise NotImplementedError
import os

TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")

# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Tern API documentation · Tern API</title></head>
<body>
<header><p><strong>Tern API</strong> · <a href="/">Home</a> · <a href="/quickstart">Quickstart</a> · <a href="/reference/quotes">Quotes</a> · <a href="/reference/shipments">Shipments</a> · <a href="/reference/statuses">Statuses</a> · <a href="/changelog">Changelog</a></p></header>
<main>
<h1>Tern API documentation</h1>
<p>Tern is a parcel carrier for small shops in the UK. The Tern API quotes, books, tracks and cancels parcels.</p>
<ul>
<li><a href="/quickstart">Quickstart</a>: your first quote in five minutes.</li>
<li><a href="/reference/quotes">Quotes</a>, <a href="/reference/shipments">Shipments</a> and <a href="/reference/statuses">Statuses</a>: the reference.</li>
<li><a href="/changelog">Changelog</a>: what changed, and what is retired.</li>
</ul>
</main>
</body>
</html>

[stdout]
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date

from shop.cart import Cart
from shop.orders import Order


def quote_at_checkout(cart: Cart, postcode: str) -> int:
    """The cheapest price Tern offers to ship this cart from the warehouse to postcode, in pence."""
    raise NotImplementedError


def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
    """Every service Tern offers for this cart and postcode, as (service, price in pence, days to deliver),
    cheapest first."""
    raise NotImplementedError


def book(order: Order, service: str) -> str:
    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    raise NotImplementedError


def shipments_since(day: date) -> list[dict]:
    """Every Tern shipment created on or after day, as Tern describes them."""
    raise NotImplementedError


def order_status(shipment_id: str) -> str:
    """The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
    raise NotImplementedError


def cancel(order: Order) -> bool:
    """Cancel the order's Tern shipment. True if Tern cancelled it; False if it is too late to cancel."""
    raise NotImplementedError
import os

TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")

# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Tern API documentation · Tern API</title></head>
<body>
<header><p><strong>Tern API</strong> · <a href="/">Home</a> · <a href="/quickstart">Quickstart</a> · <a href="/reference/quotes">Quotes</a> · <a href="/reference/shipments">Shipments</a> · <a href="/reference/statuses">Statuses</a> · <a href="/changelog">Changelog</a></p></header>
<main>
<h1>Tern API documentation</h1>
<p>Tern is a parcel carrier for small shops in the UK. The Tern API quotes, books, tracks and cancels parcels.</p>
<ul>
<li><a href="/quickstart">Quickstart</a>: your first quote in five minutes.</li>
<li><a href="/reference/quotes">Quotes</a>, <a href="/reference/shipments">Shipments</a> and <a href="/reference/statuses">Statuses</a>: the reference.</li>
<li><a href="/changelog">Changelog</a>: what changed, and what is retired.</li>
</ul>
</main>
</body>
</html>
[metadata] {"noOutputExpected": false}
3
agent · Bash
cd /app; cat shop/tern.py shop/cart.py; for p in quickstart reference/quotes changelog; do curl -s localhost:8080/$p | sed 's/<[^>]*>//g'; d…
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
cd /app; cat shop/tern.py shop/cart.py; for p in quickstart reference/quotes changelog; do curl -s localhost:8080/$p | sed 's/<[^>]*>//g'; done
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request

from shop import settings


def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
         headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
    """One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
    A connection that fails or drops raises, as urllib does."""
    url = settings.TERN_API_URL.rstrip("/") + path
    if params:
        url += "?" + urllib.parse.urlencode(params)
    data = json.dumps(body).encode() if body is not None else None
    request = urllib.request.Request(url, data=data, method=method)
    request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
    request.add_header("Accept", "application/json")
    if data is not None:
        request.add_header("Content-Type", "application/json")
    for name, value in (headers or {}).items():
        request.add_header(name, value)
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            return response.status, json.loads(response.read() or b"{}")
    except urllib.error.HTTPError as e:
        raw = e.read()
        return e.code, json.loads(raw) if raw else {}
from dataclasses import dataclass, field


@dataclass(frozen=True)
class Item:
    sku: str
    name: str
    price_pence: int
    weight_kg: float


@dataclass
class Cart:
    lines: list[tuple[Item, int]] = field(default_factory=list)

    def add(self, item: Item, quantity: int = 1) -> None:
        if quantity < 1:
            raise ValueError("quantity must be at least 1")
        self.lines.append((item, quantity))

    def subtotal_pence(self) -> int:
        return sum(item.price_pence * qty for item, qty in self.lines)

    def total_weight_kg(self) -> float:
        """The packed weight, as the warehouse scales read it."""
        return round(sum(item.weight_kg * qty for item, qty in self.lines), 3)


Quickstart · Tern API

Tern API · Home · Quickstart · Quotes · Shipments · Statuses · Changelog

Quickstart
Base URL and key
Production is https://api.tern.example. Your sandbox is at the URL in your dashboard; test keys start
with tern_test_. Send the key as a bearer token on every request:
Authorization: Bearer tern_test_...
Requests and responses are JSON.

Your first quote
curl -X POST "$TERN_API_URL/v2/quotes" \
  -H "Authorization: Bearer $TERN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"from_postcode": "EH6 6QT", "to_postcode": "M1 1AE", "weight": 1200}'
Weights are in grams, as a whole number: the parcel above weighs 1.2 kg.
Amounts are in pence, as a whole number.
{
  "quotes": [
    {"id": "qt_81", "service": "express",  "amount": 1295, "currency": "GBP", "eta_days": 1},
    {"id": "qt_82", "service": "standard", "amount": 695,  "currency": "GBP", "eta_days": 3},
    {"id": "qt_83", "service": "economy",  "amount": 495,  "currency": "GBP", "eta_days": 5}
  ]
}
Quotes are not returned in price order. Next: book a shipment.





Quotes · Tern API

Tern API · Home · Quickstart · Quotes · Shipments · Statuses · Changelog

Quotes
POST /v2/quotes
Prices for one parcel on every service Tern offers between two postcodes.

FieldType
from_postcodestringWhere the parcel is collected.
to_postcodestringWhere it is delivered.
weightintegerThe packed weight in grams. Up to 20,000.

The response holds quotes, one per service (economy, standard,
express), each with an id, its amount in pence, the
currency and eta_days. They are in no particular order. A parcel over 20 kg is a
422 with "error": "too_heavy".





Changelog · Tern API

Tern API · Home · Quickstart · Quotes · Shipments · Statuses · Changelog

Changelog
2026-06-01: v1 retired
/v1/quotes is retired and will be removed on 2027-06-01. It answers with a
Deprecation header until then. Use /v2/quotes, which takes weight in grams;
v1 took kilograms.
2026-03-10: idempotent bookings
POST /v2/shipments accepts an Idempotency-Key header.

[stdout]
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request

from shop import settings


def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
         headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
    """One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
    A connection that fails or drops raises, as urllib does."""
    url = settings.TERN_API_URL.rstrip("/") + path
    if params:
        url += "?" + urllib.parse.urlencode(params)
    data = json.dumps(body).encode() if body is not None else None
    request = urllib.request.Request(url, data=data, method=method)
    request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
    request.add_header("Accept", "application/json")
    if data is not None:
        request.add_header("Content-Type", "application/json")
    for name, value in (headers or {}).items():
        request.add_header(name, value)
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            return response.status, json.loads(response.read() or b"{}")
    except urllib.error.HTTPError as e:
        raw = e.read()
        return e.code, json.loads(raw) if raw else {}
from dataclasses import dataclass, field


@dataclass(frozen=True)
class Item:
    sku: str
    name: str
    price_pence: int
    weight_kg: float


@dataclass
class Cart:
    lines: list[tuple[Item, int]] = field(default_factory=list)

    def add(self, item: Item, quantity: int = 1) -> None:
        if quantity < 1:
            raise ValueError("quantity must be at least 1")
        self.lines.append((item, quantity))

    def subtotal_pence(self) -> int:
        return sum(item.price_pence * qty for item, qty in self.lines)

    def total_weight_kg(self) -> float:
        """The packed weight, as the warehouse scales read it."""
        return round(sum(item.weight_kg * qty for item, qty in self.lines), 3)


Quickstart · Tern API

Tern API · Home · Quickstart · Quotes · Shipments · Statuses · Changelog

Quickstart
Base URL and key
Production is https://api.tern.example. Your sandbox is at the URL in your dashboard; test keys start
with tern_test_. Send the key as a bearer token on every request:
Authorization: Bearer tern_test_...
Requests and responses are JSON.

Your first quote
curl -X POST "$TERN_API_URL/v2/quotes" \
  -H "Authorization: Bearer $TERN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"from_postcode": "EH6 6QT", "to_postcode": "M1 1AE", "weight": 1200}'
Weights are in grams, as a whole number: the parcel above weighs 1.2 kg.
Amounts are in pence, as a whole number.
{
  "quotes": [
    {"id": "qt_81", "service": "express",  "amount": 1295, "currency": "GBP", "eta_days": 1},
    {"id": "qt_82", "service": "standard", "amount": 695,  "currency": "GBP", "eta_days": 3},
    {"id": "qt_83", "service": "economy",  "amount": 495,  "currency": "GBP", "eta_days": 5}
  ]
}
Quotes are not returned in price order. Next: book a shipment.





Quotes · Tern API

Tern API · Home · Quickstart · Quotes · Shipments · Statuses · Changelog

Quotes
POST /v2/quotes
Prices for one parcel on every service Tern offers between two postcodes.

FieldType
from_postcodestringWhere the parcel is collected.
to_postcodestringWhere it is delivered.
weightintegerThe packed weight in grams. Up to 20,000.

The response holds quotes, one per service (economy, standard,
express), each with an id, its amount in pence, the
currency and eta_days. They are in no particular order. A parcel over 20 kg is a
422 with "error": "too_heavy".





Changelog · Tern API

Tern API · Home · Quickstart · Quotes · Shipments · Statuses · Changelog

Changelog
2026-06-01: v1 retired
/v1/quotes is retired and will be removed on 2027-06-01. It answers with a
Deprecation header until then. Use /v2/quotes, which takes weight in grams;
v1 took kilograms.
2026-03-10: idempotent bookings
POST /v2/shipments accepts an Idempotency-Key header.
[metadata] {"noOutputExpected": false}
4
agent · Bash
cd /app; cat > /tmp/p.py <<'E'
Traceback (most recent call last):
inline-script
cd /app; cat > /tmp/p.py <<'E'
import re
p='shop/shipping.py'
s=open(p).read()
s=s.replace('''    cheapest first."""
    raise NotImplementedError''','''    cheapest first."""
    grams = round(cart.total_weight_kg() * 1000)
    status, body = tern.call("POST", "/v2/quotes", {
        "from_postcode": settings.WAREHOUSE_POSTCODE,
        "to_postcode": postcode,
        "weight": grams,
    })
    if status != 200:
        raise RuntimeError(f"Tern quote failed ({status}): {body}")
    options = [(q["service"], q["amount"], q["eta_days"]) for q in body["quotes"]]
    return sorted(options, key=lambda o: (o[1], o[2]))''',1)
s=s.replace("from shop.cart","from shop import settings, tern\nfrom shop.cart",1)
open(p,'w').write(s)
E
python3 /tmp/p.py
python3 -c "
from shop.cart import *;from shop.shipping import *
c=Cart();c.add(Item('a','t',500,0.4),3)
print(quote_options(c,'M1 1AE'))
c.add(Item('b','t',500,0.0004),1);print(quote_options(c,'M1 1AE'))
c.add(Item('b','t',500,30),1);print(quote_options(c,'M1 1AE'))"; python3 -m pytest -q 2>&1|tail -3
Traceback (most recent call last):
  File "<string>", line 6, in <module>
    c.add(Item('b','t',500,30),1);print(quote_options(c,'M1 1AE'))
                                        ~~~~~~~~~~~~~^^^^^^^^^^^^
  File "/app/shop/shipping.py", line 24, in quote_options
    raise RuntimeError(f"Tern quote failed ({status}): {body}")
RuntimeError: Tern quote failed (422): {'error': 'too_heavy'}
[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]
[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]
.....                                                                    [100%]
5 passed in 0.01s

[stdout]
Traceback (most recent call last):
  File "<string>", line 6, in <module>
    c.add(Item('b','t',500,30),1);print(quote_options(c,'M1 1AE'))
                                        ~~~~~~~~~~~~~^^^^^^^^^^^^
  File "/app/shop/shipping.py", line 24, in quote_options
    raise RuntimeError(f"Tern quote failed ({status}): {body}")
RuntimeError: Tern quote failed (422): {'error': 'too_heavy'}
[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]
[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]
.....                                                                    [100%]
5 passed in 0.01s
[metadata] {"noOutputExpected": false}
5
agent
I implemented `quote_options` in `shop/shipping.py`. It returns every Tern service for the cart and postcode as `(service, pence, days)`, ch…
I implemented `quote_options` in `shop/shipping.py`. It returns every Tern service for the cart and postcode as `(service, pence, days)`, cheapest first. I ran it against the sandbox and the existing five tests still pass. I didn't add new tests. - **Request:** it posts to `/v2/quotes` (the v1 endpoint is being retired). It sends the warehouse postcode as the origin and the cart weight converted from kilograms to whole grams, as v2 expects. - **Sandbox output:** a normal cart came back as `[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]`. - **Ordering:** Tern returns quotes in no particular order, so I sort by price and break ties on days. - **Errors:** any non-200 response raises `RuntimeError`. A cart over 20 kg gets a 422 `too_heavy` from the sandbox, so checkout will see that exception for very heavy carts. If you'd rather it return an empty list or a friendlier error, say so. I left `quote_at_checkout` and the other stubs alone.