{"name":"api-postgres","title":"JSON API on Postgres","description":"A small JSON CRUD API on the service's own Postgres 18 (\"database\": \"postgres\"): DATABASE_URL is set at start, the database is archived continuously and restored on every wake.","runtime":"Node.js 22, one driver (pg 8.13.1)","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","postgres","database","node"],"next":"Create an item: curl -X POST {url}/items -H 'content-type: application/json' -d '{\"name\":\"first\"}', then curl {url}/items. Look inside with oa db sql {slug} \"select count(*) from items\".","oa_json":{"type":"service","install":"bun install --production","start":"node server.mjs","database":"postgres"},"files":[{"path":"README.md","content":"# JSON API on Postgres\n\nA small JSON CRUD API over one `items` table, on the service's **own Postgres\n18**: `\"database\": \"postgres\"` in `oa.json` makes the platform run Postgres\nin the same container and set `DATABASE_URL` (and `PGHOST`, `PGPORT`,\n`PGUSER`, `PGPASSWORD`, `PGDATABASE`) before `start` runs. Node's `http`\nmodule plus one pinned driver (`pg`). Each item has a `name`, a free-form\n`data` object (`jsonb`) and timestamps.\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, database size, routes\n```\n\nErrors are JSON `{\"code\": \"...\", \"message\": \"...\"}` with a 4xx/5xx status.\n\n## Look inside\n\n```bash\noa db status <slug>                              # state, size, archive health, last restore\noa db sql <slug> \"select count(*) from items\"    # psql as the app's role\noa db backup <slug>                              # a base backup now\noa db dump <slug> > items.dump                   # pg_dump -Fc; pg_restore it anywhere\n```\n\nThere is no connection from outside: Postgres listens on `127.0.0.1` inside\nthe container only, so `psql` from a laptop cannot reach it. Use `oa db sql`,\nor a dump.\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. |\n| `DATABASE_URL` | set by the platform | `postgres://app:...@127.0.0.1:5432/app`. Never stored in a version and not listed by `oa env`. |\n\nSet `API_KEY` with `oa env set <slug> API_KEY=...`.\n\n## How durable it is (honestly)\n\nThe database lives on the container's local disk, which is gone after every\nsleep. Durability is an archive in object storage: a base backup plus every\npiece of WAL (Postgres's write-ahead log), shipped continuously.\n\n- **A planned stop loses nothing**: a sleep, a restart, a redeploy and a\n  platform rollout all shut Postgres down cleanly and upload the last WAL\n  before the container goes.\n- **A hard crash can lose the last ~5 seconds of commits**: when a container\n  dies without a stop (out of memory, a host failure), the writes since the\n  last 5-second upload are gone. The database that comes back is consistent,\n  never half-written.\n- **Every wake is a restore**, and it grows with the database: a few seconds\n  for a small one, longer for hundreds of MB. So a database service sleeps\n  after an hour without requests (`sleep_after_s` 3600) instead of 10\n  minutes. The first request after a sleep waits for the restore.\n- **Limits**: up to 256 MB on `small` (1 GB on `medium`/`large`). Over the\n  limit the app's writes are refused (this template answers `507\n  database_full`), reads keep working, and `oa db sql` can still delete. One\n  database per service, no replicas, no external connections.\n- Removing `\"database\"` from `oa.json` keeps the archive; deleting the service\n  deletes it.\n\nFor data you cannot afford to lose a few seconds of, or anything bigger,\nuse a hosted Postgres (Neon, Supabase) and set `DATABASE_URL` yourself with\n`oa env set`.\n\n## Extend it\n\n- Add tables in `migrate()` (`CREATE TABLE IF NOT EXISTS ...`); it runs at\n  every start, after the database is ready. Migrations belong in `start`, not\n  `install`: the database is not running yet while `install` runs.\n- Any Postgres driver or ORM works with `DATABASE_URL` (Prisma, Drizzle,\n  SQLAlchemy, Django, Rails).\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 the database archive 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 (Postgres's CPU counts too). A request wakes it and it stays awake 3600 seconds (`sleep_after_s`) after the last one, so an occasional request costs about $0.03 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":"oa.json","content":"{\n  \"type\": \"service\",\n  \"install\": \"bun install --production\",\n  \"start\": \"node server.mjs\",\n  \"database\": \"postgres\"\n}\n"},{"path":"package.json","content":"{\n  \"name\": \"oa-api-postgres\",\n  \"version\": \"1.0.0\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"dependencies\": {\n    \"pg\": \"8.13.1\"\n  }\n}\n"},{"path":"server.mjs","content":"// A small JSON CRUD API on the service's own Postgres. Node's http module and\n// one driver (pg, pinned in package.json).\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, how many items, how big the database is\n//\n// The platform runs Postgres next to this process (\"database\": \"postgres\" in\n// oa.json) and sets DATABASE_URL (and PGHOST, PGPORT, PGUSER, PGPASSWORD,\n// PGDATABASE) before `start` runs. The schema is created here at start, so a\n// fresh database and a restored one both just work.\nimport http from 'node:http';\nimport pg from 'pg';\n\nconst PORT = Number(process.env.PORT ?? 8080);\n// Optional: when set, POST, PATCH, PUT and DELETE need `Authorization: Bearer <API_KEY>`.\nconst API_KEY = process.env.API_KEY ?? '';\nconst MAX_BODY = 1_000_000;\n\nif (!process.env.DATABASE_URL) {\n  console.error('DATABASE_URL is not set: publish with \"database\": \"postgres\" in oa.json');\n  process.exit(1);\n}\n\n// A small pool: `small` allows 19 connections for the app in all.\nconst pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 5, idleTimeoutMillis: 30_000 });\n// A connection the server closed (a database restart, the size limit cutting\n// sessions) must not crash the process; the pool opens a new one next time.\npool.on('error', (err) => console.error('idle connection closed:', err.message));\n\nasync function migrate() {\n  for (let attempt = 1; ; attempt++) {\n    try {\n      await pool.query(`\n        CREATE TABLE IF NOT EXISTS items (\n          id         bigserial PRIMARY KEY,\n          name       text NOT NULL CHECK (length(name) BETWEEN 1 AND 200),\n          data       jsonb NOT NULL DEFAULT '{}'::jsonb,\n          created_at timestamptz NOT NULL DEFAULT now(),\n          updated_at timestamptz NOT NULL DEFAULT now()\n        )`);\n      await pool.query('CREATE INDEX IF NOT EXISTS items_name ON items (lower(name))');\n      return;\n    } catch (err) {\n      // The platform starts this process once the database is ready; a retry\n      // covers a database that was restarted a moment ago.\n      if (attempt >= 10) throw err;\n      console.error(`migrate failed (${err.message}); retrying`);\n      await new Promise((r) => setTimeout(r, 1000));\n    }\n  }\n}\n\nconst send = (res, status, body) => {\n  const text = body === undefined ? '' : JSON.stringify(body);\n  res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(text) });\n  res.end(text);\n};\nconst fail = (res, status, code, message) => send(res, status, { code, message });\n\nfunction readJson(req) {\n  return new Promise((resolve, reject) => {\n    let size = 0;\n    const chunks = [];\n    req.on('data', (c) => {\n      size += c.length;\n      if (size > MAX_BODY) {\n        reject(Object.assign(new Error('body too large'), { status: 413 }));\n        req.destroy();\n      } else chunks.push(c);\n    });\n    req.on('end', () => {\n      if (chunks.length === 0) return resolve({});\n      try {\n        resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));\n      } catch {\n        reject(Object.assign(new Error('body is not JSON'), { status: 400 }));\n      }\n    });\n    req.on('error', reject);\n  });\n}\n\nfunction itemInput(body, partial) {\n  if (!body || typeof body !== 'object' || Array.isArray(body)) return { error: 'body must be a JSON object' };\n  const out = {};\n  if (body.name !== undefined) {\n    if (typeof body.name !== 'string' || !body.name.trim() || body.name.length > 200) return { error: 'name must be a string of 1-200 chars' };\n    out.name = body.name.trim();\n  } else if (!partial) return { error: 'name is required' };\n  if (body.data !== undefined) {\n    if (!body.data || typeof body.data !== 'object' || Array.isArray(body.data)) return { error: 'data must be a JSON object' };\n    out.data = body.data;\n  }\n  if (partial && out.name === undefined && out.data === undefined) return { error: 'send name and/or data' };\n  return { value: out };\n}\n\nasync function route(req, res) {\n  const url = new URL(req.url ?? '/', 'http://local');\n  const path = url.pathname.replace(/\\/+$/, '') || '/';\n  const writes = req.method !== 'GET' && req.method !== 'HEAD';\n  if (writes && API_KEY && req.headers.authorization !== `Bearer ${API_KEY}`) {\n    return fail(res, 401, 'unauthorized', 'Send Authorization: Bearer <API_KEY>.');\n  }\n\n  if (path === '/' && req.method === 'GET') {\n    const { rows } = await pool.query(\n      \"SELECT (SELECT count(*) FROM items)::int AS items, pg_database_size(current_database())::bigint AS bytes, current_setting('default_transaction_read_only') AS ro\",\n    );\n    return send(res, 200, {\n      service: 'api-postgres',\n      items: rows[0].items,\n      database_bytes: Number(rows[0].bytes),\n      read_only: rows[0].ro === 'on',\n      routes: ['GET /items', 'POST /items', 'GET /items/:id', 'PATCH /items/:id', 'DELETE /items/:id'],\n      storage: 'Postgres in this container (DATABASE_URL), archived continuously by the platform',\n    });\n  }\n\n  if (path === '/items' && req.method === 'GET') {\n    const limit = Math.min(Math.max(Number(url.searchParams.get('limit') ?? 50) || 50, 1), 500);\n    const offset = Math.max(Number(url.searchParams.get('offset') ?? 0) || 0, 0);\n    const q = url.searchParams.get('q');\n    const { rows } = q\n      ? await pool.query('SELECT * FROM items WHERE lower(name) LIKE $1 ORDER BY id DESC LIMIT $2 OFFSET $3', [`%${q.toLowerCase()}%`, limit, offset])\n      : await pool.query('SELECT * FROM items ORDER BY id DESC LIMIT $1 OFFSET $2', [limit, offset]);\n    return send(res, 200, { items: rows, limit, offset });\n  }\n\n  if (path === '/items' && req.method === 'POST') {\n    const input = itemInput(await readJson(req), false);\n    if (input.error) return fail(res, 400, 'invalid_request', input.error);\n    const { rows } = await pool.query('INSERT INTO items (name, data) VALUES ($1, $2) RETURNING *', [input.value.name, input.value.data ?? {}]);\n    return send(res, 201, rows[0]);\n  }\n\n  const m = /^\\/items\\/(\\d{1,18})$/.exec(path);\n  if (m) {\n    const id = m[1];\n    if (req.method === 'GET') {\n      const { rows } = await pool.query('SELECT * FROM items WHERE id = $1', [id]);\n      return rows[0] ? send(res, 200, rows[0]) : fail(res, 404, 'not_found', `No item ${id}.`);\n    }\n    if (req.method === 'PATCH' || req.method === 'PUT') {\n      const input = itemInput(await readJson(req), true);\n      if (input.error) return fail(res, 400, 'invalid_request', input.error);\n      const { rows } = await pool.query(\n        'UPDATE items SET name = COALESCE($2, name), data = COALESCE($3, data), updated_at = now() WHERE id = $1 RETURNING *',\n        [id, input.value.name ?? null, input.value.data ?? null],\n      );\n      return rows[0] ? send(res, 200, rows[0]) : fail(res, 404, 'not_found', `No item ${id}.`);\n    }\n    if (req.method === 'DELETE') {\n      const { rowCount } = await pool.query('DELETE FROM items WHERE id = $1', [id]);\n      if (!rowCount) return fail(res, 404, 'not_found', `No item ${id}.`);\n      res.writeHead(204);\n      return res.end();\n    }\n  }\n  return fail(res, 404, 'not_found', `No route ${req.method} ${path}.`);\n}\n\nconst server = http.createServer((req, res) => {\n  route(req, res).catch((err) => {\n    if (err.status) return fail(res, err.status, 'invalid_request', err.message);\n    // 25006: the platform made the database read-only because it is over its\n    // size limit; reads still work. 57P01/08xxx: the database is restarting.\n    if (err.code === '25006') {\n      return fail(res, 507, 'database_full', 'The database is over its size limit, so writes are refused; delete data to free space.');\n    }\n    if (err.code === '57P01' || String(err.code ?? '').startsWith('08') || /terminat|ECONNREFUSED|Connection terminated/i.test(err.message)) {\n      return fail(res, 503, 'database_unavailable', 'The database is restarting; retry in a few seconds.');\n    }\n    console.error(err);\n    return fail(res, 500, 'internal_error', 'Unexpected error; see the service logs.');\n  });\n});\n\nawait migrate();\nserver.listen(PORT, '0.0.0.0', () => console.log(`api-postgres listening on ${PORT}`));\n\n// A sleep, a restart or a redeploy: finish in-flight requests, close the pool.\nprocess.on('SIGTERM', () => {\n  server.close(() => pool.end().finally(() => process.exit(0)));\n  setTimeout(() => process.exit(0), 5000).unref();\n});\n"}],"file_count":4,"bytes":13356,"page":"https://openartifacts.sh/templates/api-postgres","publish":{"curl":"curl -sX POST https://openartifacts.sh/v1/publish -H \"Authorization: Bearer $OA_TOKEN\" -F type=service -F template=api-postgres -F slug=my-pg-api","mcp":{"tool":"publish_artifact","arguments":{"type":"service","template":"api-postgres","slug":"my-pg-api"}},"cli":"oa deploy --template api-postgres --slug my-pg-api"},"hint":"files is in the shape publish_artifact takes. To publish it unchanged: POST /v1/publish -F type=service -F template=api-postgres. To publish an edited copy: send your changed files alongside -F template=api-postgres (they replace the files of the same path), or publish the whole edited set without it (type=service; oa.json is among the files)."}