{"name":"api-sqlite","title":"JSON API on SQLite","description":"A small JSON CRUD API whose SQLite database survives sleeps, restarts and redeploys through snapshots in /data.","runtime":"Python 3.11, standard library","size":"small","env":[{"name":"API_KEY","required":false,"description":"When set, POST, PATCH and DELETE need Authorization: Bearer <API_KEY>; reads stay public."}],"tags":["api","crud","sqlite","database","python"],"next":"Create an item: curl -X POST {url}/items -H 'content-type: application/json' -d '{\"name\":\"first\"}', then curl {url}/items. Set API_KEY (oa env set {slug} API_KEY=...) to protect writes.","oa_json":{"type":"service","start":"python3 app.py"},"files":[{"path":"README.md","content":"# JSON API on SQLite\n\nA small JSON CRUD API over one `items` table, in Python with nothing but the\nstandard library, so there is no install step and it boots in about a second.\nEach item has a `name`, a free-form `data` object and timestamps. The data\nsurvives sleeps, restarts and redeploys.\n\n## Call it\n\n```bash\ncurl -s -X POST <url>/items -H 'content-type: application/json' \\\n  -d '{\"name\":\"first\",\"data\":{\"color\":\"blue\"}}'          # 201 {\"id\":1,...}\ncurl -s <url>/items                                       # newest first; ?limit=50&offset=0&q=fir\ncurl -s <url>/items/1\ncurl -s -X PATCH <url>/items/1 -H 'content-type: application/json' -d '{\"data\":{\"color\":\"red\"}}'\ncurl -s -X DELETE <url>/items/1                           # 204\ncurl -s <url>/                                            # counts, routes, where the data is\n```\n\nErrors are JSON `{\"code\": \"...\", \"message\": \"...\"}` with a 4xx status.\n\n## Environment\n\n| Variable | Required | What it does |\n| --- | --- | --- |\n| `API_KEY` | no | When set, `POST`, `PATCH`, `PUT` and `DELETE` need `Authorization: Bearer <API_KEY>`. Reads stay public; protect them in `require_key()` if they should not be. |\n\nSet it with `oa env set <slug> API_KEY=...` or\n`PUT /v1/artifacts/<slug>/env {\"env\":{\"API_KEY\":\"...\"}}`.\n\n## Where the data lives, and how durable it is\n\n`/data` is object storage mounted as a directory: it keeps whole files, but a\ndatabase file opened directly on it would be slow and could be corrupted by a\ncontainer stopped mid-write. So the live database is on the container's local\ndisk (`~/api.sqlite`), and `/data` holds snapshots of it:\n\n- on boot, the newest snapshot that passes SQLite's `quick_check` is copied to\n  local disk;\n- within 2 seconds of a write, SQLite's online backup API copies the live\n  database, the copy is written whole to whichever of two slots\n  (`/data/api.sqlite.a`, `/data/api.sqlite.b`) is not current, and only then\n  does the small file `/data/api.sqlite.current` switch to it. A crash between\n  the two steps leaves the pointer on the older, complete snapshot. (There is\n  no rename: on `/data` a rename is a server-side copy, and copies of files\n  over about 25 MB fail.)\n- on shutdown (a sleep, a restart, a redeploy) one last snapshot is written.\n\nWhat that means: a hard crash can lose the writes of the last 2 seconds\n(`FLUSH_AFTER_S`), and only one process may write, which is this one. It suits\na small app's data, up to tens of megabytes; each snapshot rewrites the whole\nfile, and `/data` is capped at 1 GB. It is not a database server.\n\n## Extend it\n\n- Add a table: one more `CREATE TABLE IF NOT EXISTS` next to `items`, routes in\n  `Handler.route`, and call `changed()` after every write so it is snapshotted.\n- Change the schema of an existing table with `ALTER TABLE` at boot; the\n  snapshot carries the old schema forward.\n- Keep using one process: a second writer would overwrite the other's\n  snapshots.\n\n## What it costs\n\nPrices for `small`, the size this template needs (current prices on\n[openartifacts.sh](https://openartifacts.sh/#cost)):\n\n- **Asleep:** no runtime charge. The bundle and `/data` are stored at $0.05 per GB-month.\n- **Awake:** $0.03 per awake hour, billed per minute, plus $0.216 per vCPU-hour of CPU actually used. A request wakes it and it stays awake 600 seconds (`sleep_after_s`) after the last one, so an occasional request costs about $0.005 plus a little CPU.\n- **Busy all day:** awake around the clock is $0.72 a day plus CPU.\n\nStarting it needs an hour of awake time in credit ($0.03), and an account runs\none service per $1 of balance.\n"},{"path":"app.py","content":"\"\"\"A small JSON CRUD API backed by SQLite. Python standard library only.\n\n    GET    /items             list (?limit=50&offset=0&q=text)\n    POST   /items             create  {\"name\": \"...\", \"data\": {...}}\n    GET    /items/<id>        read\n    PATCH  /items/<id>        update  {\"name\": \"...\", \"data\": {...}} (either key)\n    DELETE /items/<id>        delete\n    GET    /                  what this is, and how many items it holds\n\nWhere the data lives, and why: /data is object storage (R2) mounted as a\ndirectory. It keeps whole files across sleeps and restarts, but it rewrites a\nwhole object on every write and has no real file locking, so a SQLite file\nopened directly on it is slow and can be corrupted by a container that stops\nmid-write. So the live database is on the container's local disk, and /data\nholds a snapshot of it:\n\n  - on boot, the newest good snapshot in /data is copied to local disk;\n  - at most FLUSH_AFTER_S after a write, SQLite's online backup API copies the\n    live database to a local file, which is written whole to whichever of two\n    slots (/data/api.sqlite.a, /data/api.sqlite.b) is NOT current, and only\n    then is the small pointer /data/api.sqlite.current rewritten to name it;\n  - on SIGTERM (a sleep, a restart, a redeploy) a last snapshot is written.\n\nWhy two slots and a pointer instead of \"write a temp file, rename it over\":\non /data a rename is a server-side copy, and copies of files over ~25 MB fail\nthere. Writing a whole file and writing a tiny pointer both always work, and a\ncrash between the two leaves the pointer naming the older, complete slot.\n\nA hard crash can lose the writes of the last FLUSH_AFTER_S seconds. Run one\nprocess (this one); two writers would overwrite each other's snapshots.\n\"\"\"\n\nimport json\nimport os\nimport re\nimport shutil\nimport signal\nimport sqlite3\nimport sys\nimport threading\nimport time\nfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer\nfrom urllib.parse import parse_qs, urlsplit\n\nPORT = int(os.environ.get(\"PORT\", \"8080\"))\n# Optional: when set, POST, PATCH and DELETE need `Authorization: Bearer <API_KEY>`.\nAPI_KEY = os.environ.get(\"API_KEY\", \"\")\nDATA_DIR = os.environ.get(\"DATA_DIR\") or (\"/data\" if os.path.isdir(\"/data\") else os.path.join(os.getcwd(), \"data\"))\nSLOTS = {\"a\": os.path.join(DATA_DIR, \"api.sqlite.a\"), \"b\": os.path.join(DATA_DIR, \"api.sqlite.b\")}\nPOINTER = os.path.join(DATA_DIR, \"api.sqlite.current\")\n# A snapshot written by an earlier version of this template (one file, renamed into place).\nLEGACY_SNAPSHOT = os.path.join(DATA_DIR, \"api.sqlite\")\nLIVE = os.environ.get(\"DB_PATH\") or os.path.join(os.path.expanduser(\"~\"), \"api.sqlite\")\nFLUSH_AFTER_S = float(os.environ.get(\"FLUSH_AFTER_S\", \"2\"))\nMAX_BODY = 1_000_000\n\nlock = threading.RLock()\nstate = {\"dirty\": False, \"timer\": None, \"last_snapshot\": None}\n\n\ndef now():\n    return time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n\ndef read_pointer():\n    \"\"\"{\"slot\": \"a\"|\"b\", \"bytes\": n, \"at\": iso} or None.\"\"\"\n    try:\n        with open(POINTER) as f:\n            ptr = json.load(f)\n        return ptr if ptr.get(\"slot\") in SLOTS else None\n    except (FileNotFoundError, ValueError):\n        return None\n\n\ndef good_copy(path, expected_bytes=None):\n    \"\"\"Whether `path` is a complete, readable SQLite database.\"\"\"\n    try:\n        if expected_bytes is not None and os.path.getsize(path) != expected_bytes:\n            return False\n        probe = sqlite3.connect(f\"file:{path}?mode=ro\", uri=True)\n        try:\n            return probe.execute(\"PRAGMA quick_check\").fetchone()[0] == \"ok\"\n        finally:\n            probe.close()\n    except (OSError, sqlite3.DatabaseError):\n        return False\n\n\ndef restore():\n    \"\"\"Bring the newest good snapshot to local disk, unless local is the newer copy.\n\n    Local disk survives a process restart inside the same container; then the\n    local file may hold writes the snapshot does not have yet, and wins.\n    \"\"\"\n    os.makedirs(os.path.dirname(LIVE) or \".\", exist_ok=True)\n    ptr = read_pointer()\n    candidates = []\n    if ptr:\n        current = ptr[\"slot\"]\n        other = \"b\" if current == \"a\" else \"a\"\n        candidates = [(SLOTS[current], ptr.get(\"bytes\")), (SLOTS[other], None)]\n    candidates.append((LEGACY_SNAPSHOT, None))\n    source = next((path for path, size in candidates if os.path.exists(path) and good_copy(path, size)), None)\n    if source is None:\n        return \"no snapshot yet\" if not os.path.exists(LIVE) else \"local database (no snapshot yet)\"\n    marker = POINTER if ptr else source\n    if os.path.exists(LIVE) and os.path.getmtime(LIVE) >= os.path.getmtime(marker):\n        return \"local database (newer than the snapshot)\"\n    for suffix in (\"-journal\", \"-wal\", \"-shm\", \"\"):\n        try:\n            os.remove(LIVE + suffix)\n        except FileNotFoundError:\n            pass\n    shutil.copyfile(source, LIVE)\n    return f\"restored from {source}\"\n\n\nRESTORED = restore()\ndb = sqlite3.connect(LIVE, check_same_thread=False, isolation_level=None)\ndb.row_factory = sqlite3.Row\ndb.execute(\n    \"\"\"CREATE TABLE IF NOT EXISTS items (\n         id INTEGER PRIMARY KEY AUTOINCREMENT,\n         name TEXT NOT NULL,\n         data TEXT NOT NULL DEFAULT '{}',\n         created_at TEXT NOT NULL,\n         updated_at TEXT NOT NULL\n       )\"\"\"\n)\n\n\ndef snapshot():\n    \"\"\"Write the live database whole to the spare slot, then point at it.\"\"\"\n    with lock:\n        timer = state[\"timer\"]\n        if timer is not None:\n            timer.cancel()\n        state[\"timer\"] = None\n        if not state[\"dirty\"]:\n            return\n        local_copy = LIVE + \".snapshot\"\n        target = sqlite3.connect(local_copy)\n        try:\n            db.backup(target)\n        finally:\n            target.close()\n        os.makedirs(DATA_DIR, exist_ok=True)\n        ptr = read_pointer()\n        slot = \"b\" if ptr and ptr[\"slot\"] == \"a\" else \"a\"\n        size = os.path.getsize(local_copy)\n        shutil.copyfile(local_copy, SLOTS[slot])\n        if os.path.getsize(SLOTS[slot]) != size:\n            raise OSError(f\"snapshot slot {slot} holds {os.path.getsize(SLOTS[slot])} bytes, expected {size}\")\n        with open(POINTER, \"w\") as f:\n            json.dump({\"slot\": slot, \"bytes\": size, \"at\": now()}, f)\n        os.remove(local_copy)\n        state[\"dirty\"] = False\n        state[\"last_snapshot\"] = now()\n\n\ndef changed():\n    \"\"\"A write landed: snapshot within FLUSH_AFTER_S (one timer, not one per write).\"\"\"\n    with lock:\n        state[\"dirty\"] = True\n        if state[\"timer\"] is None:\n            timer = threading.Timer(FLUSH_AFTER_S, safe_snapshot)\n            timer.daemon = True\n            state[\"timer\"] = timer\n            timer.start()\n\n\ndef safe_snapshot():\n    try:\n        snapshot()\n    except Exception as err:  # keep serving; the next write retries\n        print(f\"snapshot failed: {err!r}\", file=sys.stderr, flush=True)\n\n\ndef row(r):\n    return {\n        \"id\": r[\"id\"],\n        \"name\": r[\"name\"],\n        \"data\": json.loads(r[\"data\"]),\n        \"created_at\": r[\"created_at\"],\n        \"updated_at\": r[\"updated_at\"],\n    }\n\n\nclass ApiError(Exception):\n    def __init__(self, status, code, message):\n        super().__init__(message)\n        self.status, self.code, self.message = status, code, message\n\n\ndef validate(body, partial):\n    if not isinstance(body, dict):\n        raise ApiError(400, \"invalid_request\", 'The body must be a JSON object such as {\"name\": \"first\", \"data\": {}}.')\n    out = {}\n    if \"name\" in body or not partial:\n        name = body.get(\"name\")\n        if not isinstance(name, str) or not name.strip() or len(name) > 500:\n            raise ApiError(400, \"invalid_request\", '\"name\" must be a non-empty string of at most 500 characters.')\n        out[\"name\"] = name.strip()\n    if \"data\" in body:\n        if not isinstance(body[\"data\"], dict):\n            raise ApiError(400, \"invalid_request\", '\"data\" must be a JSON object.')\n        out[\"data\"] = json.dumps(body[\"data\"])\n    if partial and not out:\n        raise ApiError(400, \"invalid_request\", 'Send \"name\" and/or \"data\".')\n    return out\n\n\nITEM = re.compile(r\"^/items/(\\d+)$\")\n\n\nclass Handler(BaseHTTPRequestHandler):\n    server_version = \"api-sqlite/1\"\n\n    def send_json(self, status, payload=None):\n        body = b\"\" if payload is None else json.dumps(payload).encode()\n        self.send_response(status)\n        if payload is not None:\n            self.send_header(\"content-type\", \"application/json\")\n        self.send_header(\"content-length\", str(len(body)))\n        self.end_headers()\n        self.wfile.write(body)\n\n    def read_json(self):\n        length = int(self.headers.get(\"content-length\") or 0)\n        if length > MAX_BODY:\n            raise ApiError(413, \"too_large\", f\"Bodies are limited to {MAX_BODY} bytes.\")\n        try:\n            return json.loads(self.rfile.read(length) or b\"null\")\n        except ValueError:\n            raise ApiError(400, \"invalid_request\", \"The body is not valid JSON.\")\n\n    def require_key(self):\n        if API_KEY and self.headers.get(\"authorization\", \"\") != f\"Bearer {API_KEY}\":\n            raise ApiError(401, \"unauthorized\", \"Send Authorization: Bearer <API_KEY> to change data.\")\n\n    def route(self, method):\n        url = urlsplit(self.path)\n        path = url.path.rstrip(\"/\") or \"/\"\n        match = ITEM.match(path)\n        if method == \"GET\" and path == \"/\":\n            with lock:\n                count = db.execute(\"SELECT COUNT(*) FROM items\").fetchone()[0]\n            return 200, {\n                \"name\": \"api-sqlite\",\n                \"items\": count,\n                \"endpoints\": [\"GET /items\", \"POST /items\", \"GET /items/<id>\", \"PATCH /items/<id>\", \"DELETE /items/<id>\"],\n                \"writes_need_api_key\": bool(API_KEY),\n                \"storage\": {\n                    \"live\": LIVE,\n                    \"snapshot\": (SLOTS[read_pointer()[\"slot\"]] if read_pointer() else None),\n                    \"boot\": RESTORED,\n                    \"last_snapshot\": state[\"last_snapshot\"],\n                    \"unsaved_writes\": state[\"dirty\"],\n                },\n            }\n        if method == \"GET\" and path == \"/health\":\n            return 200, {\"ok\": True}\n        if path == \"/items\" and method == \"GET\":\n            q = parse_qs(url.query)\n            limit = max(1, min(int((q.get(\"limit\") or [\"50\"])[0]), 500))\n            offset = max(0, int((q.get(\"offset\") or [\"0\"])[0]))\n            text = (q.get(\"q\") or [\"\"])[0]\n            with lock:\n                rows = db.execute(\n                    \"SELECT * FROM items WHERE name LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?\",\n                    (f\"%{text}%\", limit, offset),\n                ).fetchall()\n                total = db.execute(\"SELECT COUNT(*) FROM items WHERE name LIKE ?\", (f\"%{text}%\",)).fetchone()[0]\n            return 200, {\"items\": [row(r) for r in rows], \"total\": total, \"limit\": limit, \"offset\": offset}\n        if path == \"/items\" and method == \"POST\":\n            self.require_key()\n            fields = validate(self.read_json(), partial=False)\n            stamp = now()\n            with lock:\n                cur = db.execute(\n                    \"INSERT INTO items (name, data, created_at, updated_at) VALUES (?, ?, ?, ?)\",\n                    (fields[\"name\"], fields.get(\"data\", \"{}\"), stamp, stamp),\n                )\n                created = db.execute(\"SELECT * FROM items WHERE id = ?\", (cur.lastrowid,)).fetchone()\n            changed()\n            return 201, row(created)\n        if match:\n            item_id = int(match.group(1))\n            if method == \"GET\":\n                with lock:\n                    found = db.execute(\"SELECT * FROM items WHERE id = ?\", (item_id,)).fetchone()\n                if not found:\n                    raise ApiError(404, \"not_found\", f\"No item {item_id}.\")\n                return 200, row(found)\n            if method in (\"PATCH\", \"PUT\"):\n                self.require_key()\n                fields = validate(self.read_json(), partial=method == \"PATCH\")\n                sets = \", \".join(f\"{k} = ?\" for k in fields) + \", updated_at = ?\"\n                with lock:\n                    cur = db.execute(f\"UPDATE items SET {sets} WHERE id = ?\", (*fields.values(), now(), item_id))\n                    found = db.execute(\"SELECT * FROM items WHERE id = ?\", (item_id,)).fetchone()\n                if cur.rowcount == 0:\n                    raise ApiError(404, \"not_found\", f\"No item {item_id}.\")\n                changed()\n                return 200, row(found)\n            if method == \"DELETE\":\n                self.require_key()\n                with lock:\n                    cur = db.execute(\"DELETE FROM items WHERE id = ?\", (item_id,))\n                if cur.rowcount == 0:\n                    raise ApiError(404, \"not_found\", f\"No item {item_id}.\")\n                changed()\n                return 204, None\n        raise ApiError(404, \"not_found\", f\"No route {method} {path}. Try GET /items.\")\n\n    def handle_method(self, method):\n        try:\n            status, payload = self.route(method)\n        except ApiError as err:\n            status, payload = err.status, {\"code\": err.code, \"message\": err.message}\n        except ValueError:\n            status, payload = 400, {\"code\": \"invalid_request\", \"message\": \"limit and offset must be integers.\"}\n        self.send_json(status, payload)\n\n    def do_GET(self):\n        self.handle_method(\"GET\")\n\n    def do_POST(self):\n        self.handle_method(\"POST\")\n\n    def do_PATCH(self):\n        self.handle_method(\"PATCH\")\n\n    def do_PUT(self):\n        self.handle_method(\"PUT\")\n\n    def do_DELETE(self):\n        self.handle_method(\"DELETE\")\n\n    def log_message(self, fmt, *args):\n        sys.stderr.write(\"%s %s\\n\" % (self.address_string(), fmt % args))\n\n\ndef on_sigterm(signum, frame):\n    # The platform sends SIGTERM before a sleep, restart or redeploy and waits\n    # a few seconds: write the last snapshot, then exit cleanly.\n    safe_snapshot()\n    sys.exit(0)\n\n\nif __name__ == \"__main__\":\n    signal.signal(signal.SIGTERM, on_sigterm)\n    print(f\"api-sqlite listening on 0.0.0.0:{PORT}; live db {LIVE}; {RESTORED}\", flush=True)\n    server = ThreadingHTTPServer((\"0.0.0.0\", PORT), Handler)\n    server.daemon_threads = True\n    server.serve_forever()\n"},{"path":"oa.json","content":"{\n  \"type\": \"service\",\n  \"start\": \"python3 app.py\"\n}\n"}],"file_count":3,"bytes":17845,"page":"https://openartifacts.sh/templates/api-sqlite","publish":{"curl":"curl -sX POST https://openartifacts.sh/v1/publish -H \"Authorization: Bearer $OA_TOKEN\" -F type=service -F template=api-sqlite -F slug=my-api","mcp":{"tool":"publish_artifact","arguments":{"type":"service","template":"api-sqlite","slug":"my-api"}},"cli":"oa deploy --template api-sqlite --slug my-api"},"hint":"files is in the shape publish_artifact takes. To publish it unchanged: POST /v1/publish -F type=service -F template=api-sqlite. To publish an edited copy: send your changed files alongside -F template=api-sqlite (they replace the files of the same path), or publish the whole edited set without it (type=service; oa.json is among the files)."}