Build a JSON API with SQLite
A small REST API for a to-do list, written as one JavaScript file, with its data in a SQLite database. You'll go from an empty directory to a live HTTPS URL that answers GET, POST, PATCH and DELETE.
You need a terminal and about ten minutes. No Node, no Docker and no database server: the CLI is one binary, and the database is created with one command.
1. Install ribo and sign in
ribo is the Tissue Cloud CLI. Install it and sign in once:
curl -fsSL https://tissue.systems/install.sh | sh
ribo loginribo login opens a browser. If you don't have a Tissue Cloud account yet, you can create one there. The quick start has per-platform install steps and a way to check the binary's signature.
2. Create the database
mkdir todo-api && cd todo-api
ribo db create todosThat makes an empty SQLite database called todos in your account. It has no tables yet; the code creates them.
3. Write the config
Create ribo.toml. It names the Cell, points at the code, and binds the database to the name DB:
ribo.toml
[cell]
name = "todo-api"
js = "./cell.js"
[[bindings]]
type = "c3"
binding = "DB"
database = "todos"The binding is the whole connection setup. There's no connection string or password: inside the code the database is env.DB.
4. Write the API
cell.js
const SCHEMA = `
CREATE TABLE IF NOT EXISTS todos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`;
export default {
async fetch(request, env) {
const url = new URL(request.url);
const parts = url.pathname.split("/").filter(Boolean);
if (parts[0] !== "todos" || parts.length > 2) {
return json({ error: "not found" }, 404);
}
await env.DB.exec(SCHEMA);
try {
if (parts.length === 1) {
if (request.method === "GET") return await list(env.DB);
if (request.method === "POST") return await create(env.DB, request);
return json({ error: "method not allowed" }, 405);
}
const id = Number(parts[1]);
if (!Number.isInteger(id) || id < 1) return json({ error: "not found" }, 404);
if (request.method === "GET") return await show(env.DB, id);
if (request.method === "PATCH") return await update(env.DB, id, request);
if (request.method === "DELETE") return await remove(env.DB, id);
return json({ error: "method not allowed" }, 405);
} catch (err) {
return json({ error: err.message }, err.status ?? 500);
}
},
};
async function list(db) {
const { results } = await db.prepare(
"SELECT id, title, done, created_at FROM todos ORDER BY id DESC LIMIT 100"
).all();
return json(results.map(toTodo));
}
async function create(db, request) {
const body = await readJson(request);
const title = typeof body.title === "string" ? body.title.trim() : "";
if (!title || title.length > 500) throw httpError(400, "title must be 1 to 500 characters");
const { meta } = await db.prepare("INSERT INTO todos (title) VALUES (?)").bind(title).run();
return show(db, meta.last_insert_rowid, 201);
}
async function show(db, id, status = 200) {
const row = await db.prepare(
"SELECT id, title, done, created_at FROM todos WHERE id = ?"
).bind(id).first();
if (!row) return json({ error: "not found" }, 404);
return json(toTodo(row), status);
}
async function update(db, id, request) {
const body = await readJson(request);
const title = body.title === undefined ? null : String(body.title).trim();
const done = body.done === undefined ? null : Boolean(body.done);
if (title !== null && (!title || title.length > 500)) {
throw httpError(400, "title must be 1 to 500 characters");
}
// COALESCE keeps the stored value for any field the request left out.
const { meta } = await db.prepare(
"UPDATE todos SET title = COALESCE(?, title), done = COALESCE(?, done) WHERE id = ?"
).bind(title, done, id).run();
if (meta.rows_affected === 0) return json({ error: "not found" }, 404);
return show(db, id);
}
async function remove(db, id) {
const { meta } = await db.prepare("DELETE FROM todos WHERE id = ?").bind(id).run();
if (meta.rows_affected === 0) return json({ error: "not found" }, 404);
return new Response(null, { status: 204 });
}
// SQLite has no boolean type, so done is stored as 0 or 1.
function toTodo(row) {
return { ...row, done: row.done === 1 };
}
async function readJson(request) {
try {
return await request.json();
} catch {
throw httpError(400, "body must be JSON");
}
}
function httpError(status, message) {
const err = new Error(message);
err.status = status;
return err;
}
function json(data, status = 200) {
return Response.json(data, { status });
}A few things worth knowing about how this runs:
exec(SCHEMA)runs on every request.CREATE TABLE IF NOT EXISTSis a cheap no-op once the table is there, so there's no separate migration step for a project this size. c3 overview has a versioned pattern for when the schema starts changing.- Every value from the request goes through
prepare().bind(), never into the SQL string. That's what keeps a title like'); DROP TABLE todos; --from doing anything. run()returnsmeta.last_insert_rowidandmeta.rows_affected, which is how the handlers get the new id and tell a missing row from an updated one.
5. Deploy
ribo deployaccount Demo (acct_33ed412f7bca84b0) [unpinned]
server https://api.tissue.systems
deployed todo-api
address 33ed412f7x2kp
kind js
url https://todo-api.strand-9c.tissue.dev
c3 DB→todosYour url will have your own account's subdomain in place of strand-9c. Copy it into a shell variable for the next step:
API=https://todo-api.strand-9c.tissue.dev6. Try it
# create two
curl -s -X POST $API/todos -H 'content-type: application/json' -d '{"title":"Buy coffee"}'
curl -s -X POST $API/todos -H 'content-type: application/json' -d '{"title":"Write the README"}'
# list them
curl -s $API/todos
# mark the first one done
curl -s -X PATCH $API/todos/1 -H 'content-type: application/json' -d '{"done":true}'
# delete the second
curl -s -X DELETE $API/todos/2 -iThe POST answers 201 with the new row:
{"id":1,"title":"Buy coffee","done":false,"created_at":"2026-12-02 17:04:11"}You can read the same table from your terminal, which is handy while you build:
ribo db exec todos "SELECT * FROM todos"What you have
A JSON API on a public HTTPS URL, backed by a SQLite database that persists across deploys. Edit cell.js and run ribo deploy again to ship a change; the URL stays the same and the data stays put.
Anyone who has the URL can write to it. Before you hand it out, either check a bearer token from a vault binding (the URL shortener tutorial does exactly that), or put an access policy in front of it.
Next steps
- c3 API reference:
exec,batch,prepare,bindand the terminal methods - Build a URL shortener: the same pattern with redirects and a token on the write routes
- Writing Cells: routing, reading request bodies, outbound
fetch - What is SQLite at the edge?: where c3 keeps the database