Code examples
Each example is a file in examples/, and CI runs it against the live development API. If the API changes in a way that breaks an example, the docs build fails.
Storefront: read the business and list products
Section titled “Storefront: read the business and list products”Uses the public demo publishable key. Safe to run anywhere.
#!/usr/bin/env bash# Storefront API: read the business, then list three products with prices. Needs only curl.set -euo pipefailAPI="${SEDRA_API_URL:-https://api.sedra.one}"PK="${SEDRA_PUBLISHABLE_KEY:-pk_ccc8aa9718ae70bac46d4c9172f8cb3a5e8faf0dc521c30248239725d12ca241}" # public demo key
curl -fsS "$API/store/foulad/tenant" -H "x-publishable-api-key: $PK"echoREGION=$(curl -fsS "$API/store/foulad/tenant" -H "x-publishable-api-key: $PK" | sed -E 's/.*"region_id":"([^"]+)".*/\1/')curl -fsS "$API/store/products?limit=3®ion_id=$REGION&fields=id,title,handle,*variants.calculated_price" -H "x-publishable-api-key: $PK"echo// Storefront API with fetch (Node 22+, Deno, Bun or the browser). No SDK required.const API = process.env.SEDRA_API_URL ?? "https://api.sedra.one"const PK = process.env.SEDRA_PUBLISHABLE_KEY ?? "pk_ccc8aa9718ae70bac46d4c9172f8cb3a5e8faf0dc521c30248239725d12ca241" // public demo key
async function store(path) { const r = await fetch(API + path, { headers: { "x-publishable-api-key": PK } }) if (!r.ok) throw new Error(`${r.status} ${await r.text()}`) return r.json()}
const { tenant } = await store("/store/foulad/tenant")const { products } = await store(`/store/products?limit=3®ion_id=${tenant.region_id}&fields=id,title,handle,*variants.calculated_price`)const money = new Intl.NumberFormat("en-BH", { style: "currency", currency: tenant.currency_code.toUpperCase() })console.log(tenant.name)for (const p of products) console.log(`- ${p.title}: ${money.format(p.variants[0].calculated_price.calculated_amount)}`)"""Storefront API with the Python standard library (3.8+). No SDK required."""import jsonimport osimport urllib.request
API = os.environ.get("SEDRA_API_URL", "https://api.sedra.one")PK = os.environ.get("SEDRA_PUBLISHABLE_KEY", "pk_ccc8aa9718ae70bac46d4c9172f8cb3a5e8faf0dc521c30248239725d12ca241") # public demo key
def store(path: str) -> dict: req = urllib.request.Request(API + path, headers={"x-publishable-api-key": PK, "user-agent": "sedra-example/1"}) with urllib.request.urlopen(req, timeout=20) as r: return json.load(r)
tenant = store("/store/foulad/tenant")["tenant"]products = store(f"/store/products?limit=3®ion_id={tenant['region_id']}&fields=id,title,handle,*variants.calculated_price")["products"]print(tenant["name"])for p in products: amount = p["variants"][0]["calculated_price"]["calculated_amount"] print(f"- {p['title']}: {amount:.3f} {tenant['currency_code'].upper()}")// Storefront API with URLSession (Swift 5.9+, iOS 15+/macOS 12+). Run: swift Storefront.swiftimport Foundation#if canImport(FoundationNetworking)import FoundationNetworking#endif
let api = ProcessInfo.processInfo.environment["SEDRA_API_URL"] ?? "https://api.sedra.one"let publishableKey = ProcessInfo.processInfo.environment["SEDRA_PUBLISHABLE_KEY"] ?? "pk_ccc8aa9718ae70bac46d4c9172f8cb3a5e8faf0dc521c30248239725d12ca241" // public demo key
struct TenantEnvelope: Decodable { let tenant: Tenant }struct Tenant: Decodable { let name: String; let handle: String; let region_id: String; let currency_code: String }struct ProductList: Decodable { let products: [Product] }struct Product: Decodable { let title: String let variants: [Variant] struct Variant: Decodable { let calculated_price: Price? } struct Price: Decodable { let calculated_amount: Double }}
func store<T: Decodable>(_ path: String, as: T.Type) async throws -> T { var request = URLRequest(url: URL(string: api + path)!) request.setValue(publishableKey, forHTTPHeaderField: "x-publishable-api-key") let (data, response) = try await URLSession.shared.data(for: request) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) } return try JSONDecoder().decode(T.self, from: data)}
let tenant = try await store("/store/foulad/tenant", as: TenantEnvelope.self).tenantlet list = try await store("/store/products?limit=3®ion_id=\(tenant.region_id)&fields=id,title,*variants.calculated_price", as: ProductList.self)print(tenant.name)for p in list.products { let amount = p.variants.first?.calculated_price?.calculated_amount ?? 0 print("- \(p.title): \(String(format: "%.3f", amount)) \(tenant.currency_code.uppercased())")}Expected output:
Foulad Store- GaN Charger 65W: 12.500 BHD- Power Bank 20,000 mAh: 15.750 BHD- USB-C Cable 2 m: 3.250 BHDMerchant Agent API: who am I, and search products
Section titled “Merchant Agent API: who am I, and search products”#!/usr/bin/env bash# Merchant Agent API (server-side only). Needs SEDRA_API_KEY (sdr_int_… or sdr_ai_…) and SEDRA_TENANT.set -euo pipefailAPI="${SEDRA_API_URL:-https://api.sedra.one}": "${SEDRA_API_KEY:?set SEDRA_API_KEY}" "${SEDRA_TENANT:?set SEDRA_TENANT, e.g. midad-store}"
curl -fsS -X POST "$API/foulad/agent/invoke/platform.whoami" \ -H "Authorization: Bearer $SEDRA_API_KEY" -H "content-type: application/json" -d '{}'echocurl -fsS -X POST "$API/foulad/agent/invoke/catalog.products.search" \ -H "Authorization: Bearer $SEDRA_API_KEY" -H "content-type: application/json" \ -d "{\"tenant\":\"$SEDRA_TENANT\",\"input\":{\"limit\":3}}"echo// Merchant Agent API (server-side only). SEDRA_API_KEY=sdr_int_… SEDRA_TENANT=midad-store node agent.mjsimport { randomUUID } from "node:crypto"const API = process.env.SEDRA_API_URL ?? "https://api.sedra.one"const KEY = process.env.SEDRA_API_KEYconst TENANT = process.env.SEDRA_TENANTif (!KEY || !TENANT) throw new Error("Set SEDRA_API_KEY and SEDRA_TENANT")
async function invoke(capability, body = {}) { const r = await fetch(`${API}/foulad/agent/invoke/${capability}`, { method: "POST", headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json" }, body: JSON.stringify(body), }) const json = await r.json() if (!json.ok) throw new Error(`${json.error.code}: ${json.error.message}`) return json}
const me = await invoke("platform.whoami")console.log("acting as", me.data.name ?? me.data.actor_id)const found = await invoke("catalog.products.search", { tenant: TENANT, input: { limit: 3 } })for (const p of found.data.products) console.log("-", p.title)
// Writes need an idempotency key. dry_run previews without changing anything.// await invoke("catalog.products.update", { tenant: TENANT, idempotency_key: randomUUID(), dry_run: true, input: { id: "prod_…", title: "New title" } })void randomUUID"""Merchant Agent API (server-side only). SEDRA_API_KEY=sdr_int_… SEDRA_TENANT=midad-store python3 agent.py"""import jsonimport osimport urllib.errorimport urllib.requestimport uuid
API = os.environ.get("SEDRA_API_URL", "https://api.sedra.one")KEY = os.environ["SEDRA_API_KEY"]TENANT = os.environ["SEDRA_TENANT"]
def invoke(capability: str, body: "dict | None" = None) -> dict: req = urllib.request.Request( f"{API}/foulad/agent/invoke/{capability}", data=json.dumps(body or {}).encode(), headers={"authorization": f"Bearer {KEY}", "content-type": "application/json", "user-agent": "sedra-example/1"}, method="POST", ) try: with urllib.request.urlopen(req, timeout=20) as r: return json.load(r) except urllib.error.HTTPError as e: err = json.load(e)["error"] raise RuntimeError(f"{err['code']}: {err['message']}") from None
me = invoke("platform.whoami")print("acting as", me["data"].get("name"))for p in invoke("catalog.products.search", {"tenant": TENANT, "input": {"limit": 3}})["data"]["products"]: print("-", p["title"])
# Writes need an idempotency key; dry_run previews without changing anything:# invoke("catalog.products.update", {"tenant": TENANT, "idempotency_key": str(uuid.uuid4()), "dry_run": True, "input": {"id": "prod_…", "title": "New"}})_ = uuidVerification
Section titled “Verification”| Example | cURL | TypeScript (Node 22) | Python 3.9 | Swift 6 (macOS) |
|---|---|---|---|---|
| Storefront | Tested | Tested | Tested | Tested |
| Agent (read-only credential) | Tested | Tested | Tested | – |
The Swift example targets iOS 15+ and macOS 12+ and uses only Foundation.