← Lesson
Idempotency
Joeven
Run
Reset
Python loads on first run
import hashlib import json INVOICES = {"INV-17": {"cents": 4000, "refunded": False, "receipt": None}} def refund(invoice_id, amount_cents): inv = INVOICES.get(invoice_id) if inv is None: return {"error": "not_found", "invoice_id": invoice_id} if amount_cents != inv["cents"]: return { "error": "invalid_args", "hint": "amount_cents must match invoice", "expected": inv["cents"], } if inv["refunded"]: return {"ok": True, "idempotent": True, "receipt": inv["receipt"]} receipt = hashlib.sha256(invoice_id.encode()).hexdigest()[:12] inv["refunded"] = True inv["receipt"] = receipt return {"ok": True, "idempotent": False, "receipt": receipt} print("first:", json.dumps(refund("INV-17", 4000))) print("retry:", json.dumps(refund("INV-17", 4000))) print("bad amount:", json.dumps(refund("INV-17", 1))) print("missing:", json.dumps(refund("INV-0", 1))) print("still one receipt", INVOICES["INV-17"]["receipt"])
Run to execute this in your browser. Nothing is sent to a server.