{"name":"node-api","title":"Node HTTP API","description":"A minimal JSON API on Node's built-in http module: no dependencies and no install step, so it boots in well under a second.","runtime":"Node.js 22, no dependencies","size":"small","env":[],"tags":["api","node","javascript","starter"],"next":"Try curl {url}/api/hello?name=agent and curl -X POST {url}/api/echo -d '{\"hello\":\"world\"}'. Add routes in server.mjs.","oa_json":{"type":"service","start":"node server.mjs"},"files":[{"path":"README.md","content":"# Node HTTP API\n\nA minimal JSON API on Node's built-in `http` module: one file, no\ndependencies, no install step, so a cold start is just `node server.mjs` and\nthe first request after a sleep is answered in about a second. Start here when\nyou want plain JavaScript and your own routes.\n\n## Call it\n\n```bash\ncurl -s <url>/                         # name, Node version, routes\ncurl -s \"<url>/api/hello?name=agent\"   # {\"message\":\"Hello, agent!\"}\ncurl -s -X POST <url>/api/echo -H 'content-type: application/json' -d '{\"hello\":\"world\"}'\ncurl -s <url>/api/time\n```\n\nErrors are JSON `{\"code\": \"...\", \"message\": \"...\"}` with a 4xx or 5xx status.\n\n## Environment\n\nNone needed. The platform sets `PORT` (the server listens on `0.0.0.0:$PORT`)\nand `OA_URL` (this service's public URL). Add your own with\n`oa env set <slug> KEY=value` or `PUT /v1/artifacts/<slug>/env`, and read them\nfrom `process.env`.\n\n## Extend it\n\n- Add a route: a `'METHOD /path'` key in `routes` in `server.mjs`. A handler\n  gets `{url, body, req}` and returns `[status, payload]`; throw\n  `new HttpError(status, code, message)` to refuse a request.\n- Add a dependency: create a `package.json`, add an `\"install\": \"npm ci\"` (or\n  `\"npm install\"`) line to `oa.json`, and publish the lockfile with it. The\n  install runs on the first boot and its result is stored, so later wakes\n  restore it in seconds; a `\"build\"` line (for example `\"npm run build\"`)\n  runs after it and is stored with it.\n- Keep state in `/data`, written whole (write a sibling file, then rename it);\n  everything else in the container is rebuilt on each boot.\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 is 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":"oa.json","content":"{\n  \"type\": \"service\",\n  \"start\": \"node server.mjs\"\n}\n"},{"path":"server.mjs","content":"/**\n * A minimal JSON HTTP API on Node's built-in http module: no dependencies, no\n * install step, so a cold start is just `node server.mjs`.\n *\n *   GET  /                 what this is and its routes\n *   GET  /health           {\"ok\": true}\n *   GET  /api/hello        {\"message\": \"Hello, <name>!\"}   (?name=...)\n *   POST /api/echo         echoes a JSON body back with its size\n *   GET  /api/time         the server's clock\n *\n * Add a route: put a \"METHOD /path\" key in `routes`. A handler gets\n * {url, body, req} and returns [status, payload]; throwing an HttpError\n * answers with its status and a {code, message} body.\n */\nimport { createServer } from 'node:http';\n\nconst PORT = Number(process.env.PORT ?? 8080);\nconst MAX_BODY = 1_000_000;\nconst started = Date.now();\n\nclass HttpError extends Error {\n  constructor(status, code, message) {\n    super(message);\n    this.status = status;\n    this.code = code;\n  }\n}\n\nconst routes = {\n  'GET /': () => [200, {\n    name: 'node-api',\n    node: process.version,\n    uptime_s: Math.round((Date.now() - started) / 1000),\n    routes: Object.keys(routes),\n  }],\n  'GET /health': () => [200, { ok: true }],\n  'GET /api/hello': ({ url }) => {\n    const name = (url.searchParams.get('name') ?? 'world').slice(0, 100);\n    return [200, { message: `Hello, ${name}!` }];\n  },\n  'POST /api/echo': ({ body }) => {\n    if (body === undefined) throw new HttpError(400, 'invalid_request', 'Send a JSON body, e.g. {\"hello\": \"world\"}.');\n    return [200, { received: body, bytes: Buffer.byteLength(JSON.stringify(body)) }];\n  },\n  'GET /api/time': () => [200, { iso: new Date().toISOString(), epoch_ms: Date.now() }],\n};\n\n/** The request body parsed as JSON (undefined when empty); 413 past MAX_BODY. */\nasync function readJson(req) {\n  const chunks = [];\n  let size = 0;\n  for await (const chunk of req) {\n    size += chunk.length;\n    if (size > MAX_BODY) throw new HttpError(413, 'too_large', `Bodies are limited to ${MAX_BODY} bytes.`);\n    chunks.push(chunk);\n  }\n  if (size === 0) return undefined;\n  try {\n    return JSON.parse(Buffer.concat(chunks).toString('utf8'));\n  } catch {\n    throw new HttpError(400, 'invalid_request', 'The body is not valid JSON.');\n  }\n}\n\nfunction send(res, status, payload) {\n  const body = JSON.stringify(payload);\n  res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) });\n  res.end(body);\n}\n\nconst server = createServer(async (req, res) => {\n  const url = new URL(req.url ?? '/', 'http://localhost');\n  const path = url.pathname.replace(/\\/+$/, '') || '/';\n  const handler = routes[`${req.method} ${path}`];\n  try {\n    if (!handler) throw new HttpError(404, 'not_found', `No route ${req.method} ${path}. GET / lists them.`);\n    const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : await readJson(req);\n    const [status, payload] = await handler({ url, body, req });\n    send(res, status, payload);\n  } catch (err) {\n    if (err instanceof HttpError) return send(res, err.status, { code: err.code, message: err.message });\n    console.error(err);\n    send(res, 500, { code: 'internal', message: 'Something broke; the logs have the stack.' });\n  }\n});\n\n// The platform sends SIGTERM before a sleep or a restart: finish in-flight requests, then exit.\nprocess.on('SIGTERM', () => server.close(() => process.exit(0)));\n\nserver.listen(PORT, '0.0.0.0', () => console.log(`node-api listening on 0.0.0.0:${PORT}`));\n"}],"file_count":3,"bytes":5753,"page":"https://openartifacts.sh/templates/node-api","publish":{"curl":"curl -sX POST https://openartifacts.sh/v1/publish -H \"Authorization: Bearer $OA_TOKEN\" -F type=service -F template=node-api -F slug=my-node-api","mcp":{"tool":"publish_artifact","arguments":{"type":"service","template":"node-api","slug":"my-node-api"}},"cli":"oa deploy --template node-api --slug my-node-api"},"hint":"files is in the shape publish_artifact takes. To publish it unchanged: POST /v1/publish -F type=service -F template=node-api. To publish an edited copy: send your changed files alongside -F template=node-api (they replace the files of the same path), or publish the whole edited set without it (type=service; oa.json is among the files)."}