Storefront API
A read-only HTTP/JSON API over one pharmacy's wholesale catalogue: products, prices, availability and shop details. Enough to build a storefront, a price list or a stock feed, and deliberately not enough to do anything else.
Build with an agent
Most people building against this will hand it to an assistant. Copy the block below into Claude, Cursor or whatever you use, then ask for what you want. It has the full specification and, more usefully, the four things assistants reliably get wrong here.
An agent that can fetch URLs can read it directly from /developers/llms.txt.
Full specification, as one block
Roughly 150 lines. Paste it and describe your storefront.
# Codera PharmX: Storefront API
Read-only HTTP/JSON API over one pharmacy's WHOLESALE catalogue: products,
prices, availability, categories and shop details. Built for storefronts and
price lists.
Base URL: https://your-deployment.example.com/api/public/v1
Auth: Authorization: Bearer <key> (or X-Api-Key: <key>)
Keys: psk_live_… / psk_test_…, issued per pharmacy, revocable, scoped.
## Rules that are expensive to get wrong
1. PRICES ALREADY INCLUDE VAT. Every "price" is GROSS. Never add VAT on top.
To show the tax component, EXTRACT it: vat = price - price / (1 + rate).
The rate is "vatRatePercent" from /business. Every response repeats
"priceIncludesVat": true in meta so this cannot be missed.
2. "availability" IS A BAND, NOT A COUNT. Values: "in_stock", "low_stock",
"out_of_stock". The threshold behind "low_stock" is the pharmacy's private
reorder level and is never published. Exact numbers require the
"stock:exact" scope and are opt-in per key.
3. STOCK IS NOT LIVE. Levels reach this API only when a till syncs: within
seconds when the shop is online, not at all while it is offline. Every response carries
"stockAsOf" (ISO 8601). Show it. Say "as of 10 minutes ago", never
"in stock now". /health returns "stockAgeSeconds" for the same reason:
a large age means the shop is closed or offline, NOT that the API is down.
4. THERE IS NO ORDERING ENDPOINT, deliberately. Because of (3) you cannot
reserve against these numbers. Collect a basket and send it to the pharmacy
as a REQUEST they confirm out of band.
5. POLL THE DELTA, NOT THE CATALOGUE. Use
/stock?updatedSince=<last stockAsOf>. Items whose level did not change are
left out of the response entirely.
6. SEND If-None-Match. /products and /stock return an ETag. Send it back and an
unchanged poll answers 304 with no body, without the server reading the
catalogue at all. Most polls find nothing changed, so this is most of them.
## Endpoints
GET /products
scope: catalog:read cache: 30s
The published wholesale catalogue, paginated.
page (integer): 1-based. Default 1.
limit (integer): Default 50, maximum 200.
search (string): Matches name, code or description, case-insensitive.
category (string): A category key from /categories.
updatedSince (ISO 8601): Only products changed at or after this time.
GET /products/{code}
scope: catalog:read cache: 30s
One product by its code.
code (string): The product code, in the path.
GET /stock
scope: stock:read cache: 20s
Availability only: code and band. The cheap poll.
updatedSince (ISO 8601): Returns only items whose level changed since. Items with no change are omitted entirely.
GET /categories
scope: catalog:read cache: 5m
Category keys and labels. Only categories with published products.
GET /business
scope: catalog:read cache: 10m
Shop name, contact details, logo and the VAT rate.
GET /health
scope: catalog:read cache: none
Liveness, and how stale the stock picture is.
## Response envelope
List and single-object endpoints (all except /health):
{
"data": <object | array>,
"meta": {
"currency": "MWK",
"priceIncludesVat": true,
"stockAsOf": "2026-08-22T09:14:03.221Z",
"page": 1, "limit": 50, "total": 218, "totalPages": 5
}
}
Pagination keys appear on /products only. "count" appears on /stock and
/categories.
## Product object
{
"code": "WS-00042",
"name": "Paracetamol 500mg",
"description": "Box of 24 blisters",
"category": "analgesics",
"unit": "Box",
"unitsPerPack": 24,
"price": 12500,
"taxable": true,
"availability": "in_stock",
"updatedAt": "2026-08-21T16:02:11.000Z"
}
"unitsPerPack" is how many retail base-units are in one wholesale unit, so a
buyer can compare a box price against a per-unit one.
"quantityAvailable" (integer) is added only with the "stock:exact" scope.
## Business object
{ "name", "address", "phone", "email", "website",
"logo": "<data: URL or null>", "vatRatePercent": 17.5 }
## Health object (no envelope)
{ "status": "ok", "pharmacy", "stockAsOf", "stockAgeSeconds", "timestamp" }
## Errors
Uniform shape. Branch on "code", never on the message:
{ "error": { "code": "invalid_key", "message": "Invalid API key" } }
401 missing_key No Authorization or X-Api-Key header.
401 invalid_key Unknown, revoked or expired. Deliberately not distinguished.
403 insufficient_scope The key lacks the scope this endpoint needs.
403 storefront_disabled The pharmacy has not switched its storefront on.
403 tenant_inactive The pharmacy's account is suspended.
403 origin_not_allowed Browser request from an origin that is not allowlisted.
400 invalid_parameter A parameter was malformed, usually a bad date.
404 not_found No such product, or it is not published.
429 rate_limited Too many requests in the last minute.
500 internal_error Our fault. Safe to retry with backoff.
## Conditional requests
/products and /stock return an ETag. Keep it per URL and send it back:
GET /stock?updatedSince=2026-08-22T09:14:03.221Z
If-None-Match: W/"zEDEoaUj6RvIAf-YZ5Vxyx"
-> 304 Not Modified, empty body, same ETag
304 means nothing has changed since that tag; keep what you have and do not
advance your cursor. The tag covers stock movements AND catalogue edits
(including a product being published or hidden), so a 304 is a real "nothing
to do". It also covers the query, so each distinct URL has its own tag.
## Cursor handling
Advance your cursor only after a successful 200, and overlap it slightly:
cursor = new Date(Date.parse(meta.stockAsOf) - 5000).toISOString();
The five seconds cost you a few rows you already have (applying a band twice
is harmless) and protect against a write that lands while your request is
already in flight. Advancing to exactly meta.stockAsOf can skip it, and a
skipped change is never retried.
## Rate limits
120 requests per minute per key by default. Exceeding it returns 429. Retry
with exponential backoff. The limiter is per server instance, so treat it as
protection against a runaway client rather than as a precise quota.
## CORS
Server-to-server calls send no Origin header and are not subject to CORS.
Browser calls are allowed only from origins the pharmacy has allowlisted;
there is no wildcard, because these responses are credential-gated.
Do NOT put an API key in browser JavaScript. It is a bearer credential and
anyone who views source can take it. Call this API from your backend and
serve your own frontend from there.
## Recommended ingestion
1. Once: page /products?page=N&limit=200 until page >= meta.totalPages.
Store meta.stockAsOf as your cursor.
2. Every 60s: GET /stock?updatedSince=<cursor> with If-None-Match. On 304 do
nothing. On 200 apply the returned bands and advance the cursor to
meta.stockAsOf minus a 5s overlap.
3. Every 15m: GET /products?updatedSince=<cursor> to pick up new products and
price or name changes.
4. Daily: GET /categories and /business.
5. Display meta.stockAsOf next to availability.
Quick start
Ask the pharmacy for an API key, then check it works. Everything below assumes $KEY holds it.
export KEY="psk_live_xxxxxxxxxxxxxxxxxxxxxxxx"
curl -s "https://your-deployment.example.com/api/public/v1/health" \
-H "Authorization: Bearer $KEY"{
"status": "ok",
"pharmacy": "Sunrise Pharmacy",
"stockAsOf": "2026-08-22T09:14:03.221Z",
"stockAgeSeconds": 142,
"timestamp": "2026-08-22T09:16:25.882Z"
}Then the first page of the catalogue:
curl -s "https://your-deployment.example.com/api/public/v1/products?limit=50" \
-H "Authorization: Bearer $KEY"Authentication
Every endpoint needs a key. Keys look like psk_live_… or psk_test_…, belong to one pharmacy, and can be revoked at any time. You can send it either way, since they're the same credential:
Authorization: Bearer psk_live_xxxxxxxxxxxxxxxxxxxxxxxx
# or, equivalently
X-Api-Key: psk_live_xxxxxxxxxxxxxxxxxxxxxxxxNever ship a key to a browser
It is a bearer credential: whoever holds it has everything it grants, and anyone can read your page source. Call this API from your backend and serve your own frontend from there. The CORS allowlist below exists for genuinely browser-side integrations, not as a way to make a public key safe.
Scopes
A key grants exactly what it lists. The first two are the default; the third has to be asked for.
| Scope | Grants | Notes |
|---|---|---|
catalog:read | Products, categories and shop details | Granted by default. Required by every endpoint except /stock. |
stock:read | Availability bands | Granted by default. Required by /stock. |
stock:exact | Exact quantities | Not granted by default. Adds quantityAvailable to product and stock responses. Ask the pharmacy first, since it exposes their full inventory position. |
Four rules
Everything else is an endpoint table. These four are the ones that produce a storefront which looks correct and is wrong.
01Prices already include VAT
Every price is gross. Adding VAT on top overcharges on every line. To show the tax component, extract it:
const rate = business.vatRatePercent / 100; // e.g. 0.175
const vat = price - price / (1 + rate);
const net = price - vat;Every response repeats meta.priceIncludesVat: true so this cannot be missed by accident.
02Availability is a band, not a count
availability is one of in_stock, low_stock or out_of_stock. The threshold behind low is the pharmacy's own reorder level and is never published, because otherwise the band could be worked back into a range. Exact numbers need the stock:exact scope.
03Stock is not live
Levels reach this API when a till syncs. That's within seconds while the shop is online, and not at all while it's offline. Every response carries meta.stockAsOf. Show it. Say “as of 10 minutes ago”, never “in stock now”.
A large stockAgeSeconds from /health means the shop is closed or offline, not that the API is broken. Soften your wording rather than raising an alarm.
04There is no ordering endpoint
Deliberately. Because of rule 3 you cannot reserve against these numbers. Collect a basket and send it to the pharmacy as a request they confirm by email, WhatsApp, a form or whatever suits them. Treat every quantity here as indicative.
Endpoints
All are GET, all live under https://your-deployment.example.com/api/public/v1, and all answer OPTIONS for preflight.
/productsscope catalog:readcache 30sThe published wholesale catalogue, paginated.
pageinteger- 1-based. Default 1.
limitinteger- Default 50, maximum 200.
searchstring- Matches name, code or description, case-insensitive.
categorystring- A category key from /categories.
updatedSinceISO 8601- Only products changed at or after this time.
/products/{code}scope catalog:readcache 30sOne product by its code.
codestring- The product code, in the path.
/stockscope stock:readcache 20sAvailability only: code and band. The cheap poll.
updatedSinceISO 8601- Returns only items whose level changed since. Items with no change are omitted entirely.
/categoriesscope catalog:readcache 5mCategory keys and labels. Only categories with published products.
/businessscope catalog:readcache 10mShop name, contact details, logo and the VAT rate.
/healthscope catalog:readcache noneLiveness, and how stale the stock picture is.
Response shapes
Everything except /health comes wrapped in the same envelope, so a client can unwrap once.
{
"data": [
{
"code": "WS-00042",
"name": "Paracetamol 500mg",
"description": "Box of 24 blisters",
"category": "analgesics",
"unit": "Box",
"unitsPerPack": 24,
"price": 12500,
"taxable": true,
"availability": "in_stock",
"updatedAt": "2026-08-21T16:02:11.000Z"
}
],
"meta": {
"currency": "MWK",
"priceIncludesVat": true,
"page": 1,
"limit": 2,
"total": 218,
"totalPages": 109,
"stockAsOf": "2026-08-22T09:14:03.221Z"
}
}unitsPerPack is how many retail base-units are in one wholesale unit (24 blisters in a box, say), so a buyer can compare a box price against a per-unit one. quantityAvailable appears only with the stock:exact scope.
{
"data": [
{ "code": "WS-00042", "availability": "in_stock" },
{ "code": "WS-00117", "availability": "out_of_stock" }
],
"meta": {
"currency": "MWK",
"priceIncludesVat": true,
"count": 2,
"stockAsOf": "2026-08-22T09:31:44.010Z"
}
}export type Availability = "in_stock" | "low_stock" | "out_of_stock";
export interface Envelope<T> {
data: T;
meta: {
currency: string;
priceIncludesVat: true;
stockAsOf?: string | null;
page?: number;
limit?: number;
total?: number;
totalPages?: number;
count?: number;
};
}
export interface Product {
code: string;
name: string;
description: string;
category: string;
unit: string;
unitsPerPack: number;
/** GROSS. VAT is already included. Never add it. */
price: number;
taxable: boolean;
availability: Availability;
updatedAt: string | null;
/** Only with the stock:exact scope. */
quantityAvailable?: number;
}
export interface StockEntry {
code: string;
availability: Availability;
quantityAvailable?: number;
}
export interface Business {
name: string;
address: string;
phone: string;
email: string;
website: string;
logo: string | null;
vatRatePercent: number;
}Ingesting the data
Pull the catalogue once, then poll only what changes. The updatedSince parameter is what makes a frequent poll cheap for both sides. Items whose level didn't change are left out of the response entirely.
const API = "https://your-deployment.example.com/api/public/v1";
const KEY = process.env.PHARMX_API_KEY;
async function get(path) {
const res = await fetch(API + path, {
headers: { Authorization: `Bearer ${KEY}` },
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(`${res.status} ${body.error?.code ?? "unknown"}`);
}
return res.json();
}
export async function pullCatalogue() {
const products = [];
let page = 1;
let totalPages = 1;
let stockAsOf = null;
// 200 is the maximum the API will return in one page.
do {
const { data, meta } = await get(`/products?page=${page}&limit=200`);
products.push(...data);
totalPages = meta.totalPages;
stockAsOf = meta.stockAsOf ?? stockAsOf;
page += 1;
} while (page <= totalPages);
// Keep this cursor. It is what makes every later poll a delta.
return { products, cursor: stockAsOf };
}// Overlap the cursor slightly. Applying a band twice is harmless; missing a
// write that landed while the last request was in flight is not, because a
// skipped change is never retried.
const OVERLAP_MS = 5000;
export async function pollStock(state, apply) {
const query = state.cursor
? `?updatedSince=${encodeURIComponent(state.cursor)}`
: "";
const res = await fetch(`${API}/stock${query}`, {
headers: {
Authorization: `Bearer ${KEY}`,
// Most polls find nothing changed. This turns those into a 304 with no
// body, and the server never reads the catalogue.
...(state.etag ? { "If-None-Match": state.etag } : {}),
},
});
if (res.status === 304) return state; // nothing to do
if (!res.ok) throw new Error(`stock poll: ${res.status}`);
const { data, meta } = await res.json();
for (const entry of data) apply(entry.code, entry.availability);
return {
etag: res.headers.get("ETag") ?? state.etag,
cursor: meta.stockAsOf
? new Date(Date.parse(meta.stockAsOf) - OVERLAP_MS).toISOString()
: state.cursor,
};
}A sensible schedule
| How often | Call | Why |
|---|---|---|
| Every 60s | /stock?updatedSince=… | Availability moves constantly. |
| Every 15m | /products?updatedSince=… | New products, price and name changes. |
| Daily | /categories, /business | Rarely change at all. |
| On demand | /health | Show staleness; alert only on non-200. |
import os, requests
API = "https://your-deployment.example.com/api/public/v1"
KEY = os.environ["PHARMX_API_KEY"]
SESSION = requests.Session()
SESSION.headers["Authorization"] = f"Bearer {KEY}"
def get(path):
r = SESSION.get(API + path, timeout=20)
if not r.ok:
code = (r.json().get("error") or {}).get("code", "unknown")
raise RuntimeError(f"{r.status_code} {code}")
return r.json()
def pull_catalogue():
products, page, total_pages, cursor = [], 1, 1, None
while page <= total_pages:
body = get(f"/products?page={page}&limit=200")
products += body["data"]
total_pages = body["meta"]["totalPages"]
cursor = body["meta"].get("stockAsOf") or cursor
page += 1
return products, cursorConditional requests
/products and /stock return an ETag. Keep it per URL and send it back on the next poll. Most polls find nothing changed, so most of them become a 304 with no body, and the server answers without reading the catalogue at all.
GET /stock?updatedSince=2026-08-22T09:14:03.221Z
Authorization: Bearer $KEY
If-None-Match: W/"zEDEoaUj6RvIAf-YZ5Vxyx"
HTTP/1.1 304 Not Modified
ETag: W/"zEDEoaUj6RvIAf-YZ5Vxyx"
Cache-Control: public, max-age=20The tag covers stock movements and catalogue edits, including a product being published or hidden, so a 304 genuinely means “nothing to do”. It also covers the query, so each distinct URL has its own tag. On a 304, keep what you have and do not advance your cursor.
Overlap your cursor
Advance it to slightly before meta.stockAsOf, not to it:
cursor = new Date(Date.parse(meta.stockAsOf) - 5000).toISOString();Those five seconds cost you a few rows you already have (applying the same band twice changes nothing) and protect against a write landing while your request was already in flight. Advancing to exactly stockAsOf can step over it, and a skipped change is never offered again.
How fresh can this get? Not fresher than the till. Levels reach the server on sync, which is every 20 to 120 seconds while the shop is online and not at all while it's offline. Polling faster than a minute buys you nothing but requests.
Errors & limits
Every failure has the same shape. Branch on code, never on the message. Messages are for humans and may be reworded.
{ "error": { "code": "invalid_key", "message": "Invalid API key" } }| Status | Code | Meaning |
|---|---|---|
| 401 | missing_key | No Authorization or X-Api-Key header. |
| 401 | invalid_key | Unknown, revoked or expired. Deliberately not distinguished. |
| 403 | insufficient_scope | The key lacks the scope this endpoint needs. |
| 403 | storefront_disabled | The pharmacy has not switched its storefront on. |
| 403 | tenant_inactive | The pharmacy's account is suspended. |
| 403 | origin_not_allowed | Browser request from an origin that is not allowlisted. |
| 400 | invalid_parameter | A parameter was malformed, usually a bad date. |
| 404 | not_found | No such product, or it is not published. |
| 429 | rate_limited | Too many requests in the last minute. |
| 500 | internal_error | Our fault. Safe to retry with backoff. |
Unknown, revoked and expired all answer the same: 401 invalid_key. Distinguishing them would tell an attacker which of their guesses was once a real key.
Rate limits
120 requests per minute per key by default; beyond that you get 429 rate_limited. Back off exponentially. Be aware the limiter is per server instance, so treat it as protection against a runaway client rather than a precise quota. Don't build billing or hard scheduling on the exact number.
Responses carry short Cache-Control lifetimes (20s to 10m, listed per endpoint above). Honour them and you will rarely come close to the limit.
Browsers & CORS
Server-to-server calls (your backend, a cron job, curl) send no Origin header and are not subject to CORS at all. That is the intended way to use this API.
Browser calls are allowed only from origins the pharmacy has explicitly allowlisted. There is no wildcard and never will be: these responses are credential-gated, so * would let any page that obtained the key read them. Ask the pharmacy to add your exact origin, scheme and port included.
https://shop.example.com ✓ exact match
https://shop.example.com:443 ✗ different string
http://shop.example.com ✗ different scheme
https://www.shop.example.com ✗ different hostGetting a key
Keys are issued per pharmacy. The pharmacy must switch its storefront on (until then every call answers 403 storefront_disabled, even with a valid key) and then ask us to issue one, choosing the scopes and any browser origins it may be used from.
The key is shown once at creation and only its hash is stored, so it cannot be recovered later. If it is lost, it is revoked and replaced.