Tutorial: a REST API
This tutorial builds a small but complete API for notes, from an empty folder to a Docker image. Along the way it uses most of what the package does:
- one schema per resource, with the request and response shapes derived from it;
- a password that the API accepts but never returns, and ids that clients can send but never set;
- query strings coerced into numbers and booleans, with defaults;
- a PATCH that changes only the fields it receives;
- errors a client can map to form fields;
- tests, an OpenAPI document, and deployment.
It runs on Bun with Hono and Bun's built-in SQLite. The schemas and the validation work the same on Node.js with any other framework from Framework integrations; only the database, password hashing and server calls are Bun's.
The finished project:
notes-api/
├── src/
│ ├── schemas.ts the schemas
│ ├── db.ts SQLite tables and queries
│ ├── app.ts the routes
│ ├── openapi.ts the OpenAPI document
│ ├── index.ts starts the server
│ └── app.test.ts tests
├── Dockerfile
├── .dockerignore
├── .gitignore from bun init, plus two lines
├── package.json from bun init
├── bun.lock from bun init
└── tsconfig.json from bun init1. Create the project
You need a recent Bun; this tutorial was tested with Bun 1.4.
mkdir notes-api && cd notes-api
bun init -y
rm index.ts
bun add hono @hono/standard-validator typebox-standard-schemabun init writes package.json, tsconfig.json, .gitignore and bun.lock, and may add a few files of its own, such as a README.md, that this tutorial doesn't use. Since the code lives in src/, change the "module" field in package.json from "index.ts" to "src/index.ts". Then keep the database and the compiled server out of git by adding two lines to .gitignore:
notes.sqlite*
notes-api@hono/standard-validator is Hono's middleware for any Standard Schema, which every schema built with this package is. Don't install typebox itself: it comes with this package, and you import everything from typebox-standard-schema.
bun init also installs TypeScript. From step 2 on, once src/ has a file, check the types after each step with:
bunx tsc --noEmit2. Describe the data
Each resource gets one schema that describes it completely, stored fields and secrets included. Type.Readonly marks a field the server sets (an id, a timestamp), and Type.Writeonly marks one the client sends but never gets back (a password). The request and response shapes are derived from that schema rather than written a second time.
Create src/schemas.ts:
import { Type } from 'typebox-standard-schema'
const Timestamp = Type.String({ format: 'date-time' })
export const User = Type.Object({
id: Type.Readonly(Type.Integer()),
email: Type.String({ format: 'email', maxLength: 254 }),
name: Type.String({ minLength: 1, maxLength: 100 }),
password: Type.Writeonly(Type.String({ minLength: 8, maxLength: 128 })),
createdAt: Type.Readonly(Timestamp),
})
export const Note = Type.Object({
id: Type.Readonly(Type.Integer()),
title: Type.String({ minLength: 1, maxLength: 200 }),
body: Type.String({ maxLength: 10_000, default: '' }),
pinned: Type.Boolean({ default: false }),
createdAt: Type.Readonly(Timestamp),
updatedAt: Type.Readonly(Timestamp),
})
export const NewUser = Type.Write(User)
export const PublicUser = Type.Read(User)
export const Credentials = Type.Pick(NewUser, ['email', 'password'])
export const NewNote = Type.Write(Note)
export const NotePatch = Type.Partial(NewNote)
export const NoteView = Type.Read(Note)
// Project the whole page, not just its items: a new object around
// Type.Read(Note) would be a full schema again, read as its write shape.
export const NotePage = Type.Read(Type.Object({
page: Type.Integer(),
items: Type.Array(Note),
}))
export const NoteId = Type.Object({ id: Type.Integer({ minimum: 1 }) })
export const NoteSearch = Type.Object({
q: Type.Optional(Type.String({ minLength: 1 })),
pinned: Type.Optional(Type.Boolean()),
page: Type.Integer({ minimum: 1, default: 1 }),
limit: Type.Integer({ minimum: 1, maximum: 100, default: 20 }),
})The names at the bottom are the shapes the API actually uses:
| Schema | Shape | Used for |
|---|---|---|
NewUser = Type.Write(User) |
{ email, name, password } |
the sign-up body: id and createdAt are cut |
PublicUser = Type.Read(User) |
{ id, email, name, createdAt } |
every response with a user: password is cut |
Credentials |
{ email, password } |
the sign-in body: a Type.Pick of NewUser |
NewNote = Type.Write(Note) |
{ title, body, pinned } |
the body of a new note: a client may leave out body and pinned, which have defaults |
NotePatch = Type.Partial(NewNote) |
every field optional, defaults removed | the PATCH body |
NoteView = Type.Read(Note) |
the whole note | every response with a note |
NotePage |
{ page, items }, each item a whole note |
the response of the note list |
A cut field is not only missing from the type: a client that sends id with a new user has it removed before the handler runs, and a user row that still holds a password is stripped before it reaches the response. A cut field that is present is still checked against its own schema before it is removed, so "id": 99 is dropped silently while "id": "abc" is rejected with a 400, as any wrong value would be (why). See Projections.
NotePatch uses Type.Partial, which removes defaults as it makes fields optional. Without that, a PATCH of only the title would come back from validation with body: '' and pinned: false filled in, and would erase both.
NotePage projects the whole page with Type.Read, rather than putting NoteView inside a new Type.Object. A new object around a projection is a full schema again, and a full schema is read as its write shape: Type.Object({ items: Type.Array(NoteView) }) would validate, and describe in OpenAPI, notes without their id and timestamps. See Nesting projections.
NoteSearch describes the query string. Query values arrive as strings; validation converts '2' to 2 and 'true' to true, and fills in page and limit when they are absent.
3. Store it in SQLite
Create src/db.ts. It creates the tables and wraps every query the API needs:
import type { Static } from 'typebox-standard-schema'
import type { NewNote, NoteSearch, NoteView, PublicUser } from './schemas'
import { Database } from 'bun:sqlite'
export function openDatabase(path: string): Database {
const db = new Database(path, { strict: true })
db.run('PRAGMA foreign_keys = ON')
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL
)`)
db.run(`CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
)`)
db.run(`CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title TEXT NOT NULL,
body TEXT NOT NULL,
pinned INTEGER NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`)
return db
}
type UserView = Static<typeof PublicUser>
type NoteRecord = Static<typeof NoteView>
type NoteRow = Omit<NoteRecord, 'pinned'> & { pinned: number }
const userColumns = 'id, email, name, created_at AS createdAt'
const noteColumns = 'id, title, body, pinned, created_at AS createdAt, updated_at AS updatedAt'
// SQLite has no boolean type: `pinned` is stored as 0 or 1.
const toNote = (row: NoteRow): NoteRecord => ({ ...row, pinned: row.pinned === 1 })
// INSERT ... RETURNING always yields the inserted row; say so once.
function inserted<T>(row: T | null): T {
if (row === null)
throw new Error('INSERT returned no row')
return row
}
export function createStore(db: Database) {
return {
insertUser(email: string, name: string, passwordHash: string): UserView {
return inserted(db.query<UserView, [string, string, string, string]>(
`INSERT INTO users (email, name, password_hash, created_at) VALUES (?, ?, ?, ?) RETURNING ${userColumns}`,
).get(email, name, passwordHash, new Date().toISOString()))
},
findUser(id: number): UserView | null {
return db.query<UserView, [number]>(`SELECT ${userColumns} FROM users WHERE id = ?`).get(id)
},
findLogin(email: string): { id: number, passwordHash: string } | null {
return db.query<{ id: number, passwordHash: string }, [string]>(
'SELECT id, password_hash AS passwordHash FROM users WHERE email = ?',
).get(email)
},
insertSession(tokenHash: string, userId: number): void {
db.run('INSERT INTO sessions (token_hash, user_id) VALUES (?, ?)', [tokenHash, userId])
},
findSessionUser(tokenHash: string): number | null {
return db.query<{ userId: number }, [string]>(
'SELECT user_id AS userId FROM sessions WHERE token_hash = ?',
).get(tokenHash)?.userId ?? null
},
deleteSession(tokenHash: string): void {
db.run('DELETE FROM sessions WHERE token_hash = ?', [tokenHash])
},
insertNote(userId: number, note: Static<typeof NewNote>): NoteRecord {
const now = new Date().toISOString()
return toNote(inserted(db.query<NoteRow, [number, string, string, number, string, string]>(
`INSERT INTO notes (user_id, title, body, pinned, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?) RETURNING ${noteColumns}`,
).get(userId, note.title, note.body, Number(note.pinned), now, now)))
},
findNote(userId: number, id: number): NoteRecord | null {
const row = db.query<NoteRow, [number, number]>(
`SELECT ${noteColumns} FROM notes WHERE user_id = ? AND id = ?`,
).get(userId, id)
return row && toNote(row)
},
searchNotes(userId: number, search: Static<typeof NoteSearch>): NoteRecord[] {
return db.query<NoteRow, Record<string, string | number | null>>(
`SELECT ${noteColumns} FROM notes
WHERE user_id = $userId
AND ($q IS NULL OR title LIKE '%' || $q || '%')
AND ($pinned IS NULL OR pinned = $pinned)
ORDER BY pinned DESC, updated_at DESC
LIMIT $limit OFFSET $offset`,
).all({
userId,
q: search.q ?? null,
pinned: search.pinned === undefined ? null : Number(search.pinned),
limit: search.limit,
offset: (search.page - 1) * search.limit,
}).map(toNote)
},
updateNote(userId: number, id: number, note: Static<typeof NewNote>): NoteRecord | null {
const row = db.query<NoteRow, [string, string, number, string, number, number]>(
`UPDATE notes SET title = ?, body = ?, pinned = ?, updated_at = ?
WHERE id = ? AND user_id = ? RETURNING ${noteColumns}`,
).get(note.title, note.body, Number(note.pinned), new Date().toISOString(), id, userId)
return row && toNote(row)
},
deleteNote(userId: number, id: number): boolean {
return db.run('DELETE FROM notes WHERE id = ? AND user_id = ?', [id, userId]).changes > 0
},
}
}
export type Store = ReturnType<typeof createStore>Two things here matter for the schemas:
- Queries select the exact columns a schema describes. An object schema allows keys it doesn't declare, and
Type.Readremoves only the fields it cuts, so aSELECT *would senduser_idorpassword_hashstraight to the client. Selecting named columns (and renamingcreated_attocreatedAt) makes each row matchPublicUserorNoteViewexactly. If you'd rather have the schema reject extra keys, give itadditionalProperties: false. - The stored form is converted where it differs from the schema. SQLite has no boolean, so
pinnedcomes back as0or1. Validation converts only strings, never numbers, sotoNoteturns it into a boolean before the row goes anywhere.
Sessions store a SHA-256 hash of each token rather than the token, so a leaked database doesn't sign anyone in.
4. Write the routes
Create src/app.ts:
import type { Context } from 'hono'
import type { Store } from './db'
import { sValidator } from '@hono/standard-validator'
import { CryptoHasher, password } from 'bun'
import { SQLiteError } from 'bun:sqlite'
import { Hono } from 'hono'
import { createMiddleware } from 'hono/factory'
import { HTTPException } from 'hono/http-exception'
import { isValidationError, parse } from 'typebox-standard-schema'
import { Credentials, NewNote, NewUser, NoteId, NotePage, NotePatch, NoteSearch, NoteView, PublicUser } from './schemas'
// Answer invalid input with the issues alone. Without a hook Hono would
// also echo the rejected body back, password included.
function rejectInvalid(result: { success: boolean, error?: readonly unknown[] }, c: Context) {
if (!result.success)
return c.json({ issues: result.error }, 400)
}
const sha256 = (token: string) => new CryptoHasher('sha256').update(token).digest('hex')
export function createApp(store: Store) {
const app = new Hono()
const signedIn = createMiddleware<{ Variables: { userId: number } }>(async (c, next) => {
const token = c.req.header('Authorization')?.match(/^Bearer (\S+)$/)?.[1]
const userId = token === undefined ? null : store.findSessionUser(sha256(token))
if (userId === null)
return c.json({ error: 'unauthorized' }, 401)
c.set('userId', userId)
await next()
})
app.post('/users', sValidator('json', NewUser, rejectInvalid), async (c) => {
const { email, name, password: plain } = c.req.valid('json')
try {
const user = store.insertUser(email, name, await password.hash(plain))
return c.json(parse(PublicUser, user), 201)
}
catch (error) {
if (error instanceof SQLiteError && error.code === 'SQLITE_CONSTRAINT_UNIQUE')
return c.json({ error: 'email already registered' }, 409)
throw error
}
})
app.post('/sessions', sValidator('json', Credentials, rejectInvalid), async (c) => {
const { email, password: plain } = c.req.valid('json')
const login = store.findLogin(email)
if (!login || !(await password.verify(plain, login.passwordHash)))
return c.json({ error: 'wrong email or password' }, 401)
const token = crypto.randomUUID()
store.insertSession(sha256(token), login.id)
return c.json({ token }, 201)
})
app.delete('/sessions', signedIn, (c) => {
const token = c.req.header('Authorization')?.slice('Bearer '.length) ?? ''
store.deleteSession(sha256(token))
return c.body(null, 204)
})
app.get('/me', signedIn, (c) => {
const user = store.findUser(c.get('userId'))
if (!user)
return c.json({ error: 'unauthorized' }, 401)
return c.json(parse(PublicUser, user))
})
app.get('/notes', signedIn, sValidator('query', NoteSearch, rejectInvalid), (c) => {
const search = c.req.valid('query')
const notes = store.searchNotes(c.get('userId'), search)
return c.json(parse(NotePage, { page: search.page, items: notes }))
})
app.post('/notes', signedIn, sValidator('json', NewNote, rejectInvalid), (c) => {
const note = store.insertNote(c.get('userId'), c.req.valid('json'))
return c.json(parse(NoteView, note), 201)
})
app.get('/notes/:id', signedIn, sValidator('param', NoteId, rejectInvalid), (c) => {
const note = store.findNote(c.get('userId'), c.req.valid('param').id)
if (!note)
return c.json({ error: 'not found' }, 404)
return c.json(parse(NoteView, note))
})
app.patch(
'/notes/:id',
signedIn,
sValidator('param', NoteId, rejectInvalid),
sValidator('json', NotePatch, rejectInvalid),
(c) => {
const userId = c.get('userId')
const { id } = c.req.valid('param')
const current = store.findNote(userId, id)
if (!current)
return c.json({ error: 'not found' }, 404)
const { title, body, pinned } = current
const note = store.updateNote(userId, id, { title, body, pinned, ...c.req.valid('json') })
if (!note)
return c.json({ error: 'not found' }, 404)
return c.json(parse(NoteView, note))
},
)
app.delete('/notes/:id', signedIn, sValidator('param', NoteId, rejectInvalid), (c) => {
if (!store.deleteNote(c.get('userId'), c.req.valid('param').id))
return c.json({ error: 'not found' }, 404)
return c.body(null, 204)
})
app.notFound(c => c.json({ error: 'not found' }, 404))
app.onError((error, c) => {
// Hono's own client errors, such as a body that isn't JSON, keep their status.
if (error instanceof HTTPException)
return c.json({ error: error.message }, error.status)
// Anything else is a bug on our side: a response that fails its schema
// throws a ValidationError from parse().
console.error(isValidationError(error) ? error.issues : error)
return c.json({ error: 'internal error' }, 500)
})
return app
}Each route validates its input with sValidator(target, schema, rejectInvalid), and inside the handler c.req.valid(target) returns the validated, typed data: c.req.valid('json') on POST /users is { email: string, name: string, password: string }.
Invalid input. rejectInvalid answers 400 with the issues, one per problem, each with a path to its field and a keyword naming the rule that failed (see Issue shape). Signing up with { "email": "not-an-email", "password": "short" } gets:
{
"issues": [
{ "message": "must have required property name", "keyword": "required", "params": { "missingProperty": "name" }, "path": ["name"] },
{ "message": "must match format \"email\"", "keyword": "format", "params": { "format": "email" }, "path": ["email"] },
{ "message": "must not have fewer than 8 characters", "keyword": "minLength", "params": { "limit": 8 }, "path": ["password"] }
]
}Without the hook, Hono's own 400 would echo the rejected body back, the password included.
A JSON body is only read when the request says Content-Type: application/json. Without that header Hono validates an empty object, and the answer lists every required field as missing. If a request you're sure is complete comes back like that, check the header first.
Responses. Hono doesn't validate what you send, so every response goes through parse with a read schema. That removes write-only fields and checks the row against the schema. If a query ever returns something the schema doesn't allow, parse throws a ValidationError. app.onError logs its issues and answers 500, because a bad response is the server's fault, not the client's.
The note list is checked the same way, as one NotePage. app.notFound answers an unknown path with JSON too, so every error from the API has the same { error } shape.
app.onError sees Hono's own errors too. A body that isn't JSON at all makes Hono throw an HTTPException with status 400; the handler passes its status on, so the client gets { "error": "Malformed JSON in request body" } with a 400 rather than an internal error.
PATCH. The handler loads the current note, overlays the fields the client sent, and saves the result. Because NotePatch has no defaults, a field the client left out is absent from c.req.valid('json') and keeps its stored value.
Path parameters are strings too: for /notes/7, NoteId turns '7' into the number 7; /notes/abc gets a 400 with a type issue at ['id'].
5. Run it
Create src/index.ts. It reads the configuration from the environment, opens the database and starts the server. On Ctrl+C, or when Docker stops the container, it finishes the requests in flight and closes the database:
import { serve } from 'bun'
import { createApp } from './app'
import { createStore, openDatabase } from './db'
const { DATABASE_PATH = 'notes.sqlite', PORT = '3000' } = process.env
const db = openDatabase(DATABASE_PATH)
const app = createApp(createStore(db))
const server = serve({ port: Number(PORT), fetch: app.fetch })
console.log(`Listening on ${server.url}`)
// Finish the requests in flight and close the database on Ctrl+C or
// `docker stop`. In a container the app runs as PID 1, which ignores
// these signals unless it handles them.
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.on(signal, async () => {
await server.stop()
db.close()
process.exit(0)
})
}bun --watch src/index.tsIt listens on port 3000 and creates notes.sqlite in the current folder; set PORT and DATABASE_PATH to change either. --watch restarts the server whenever a file changes, so it picks up the next steps as you write them.
Try it from another terminal:
curl -X POST localhost:3000/users \
-H 'Content-Type: application/json' \
-d '{"email":"ann@example.com","name":"Ann","password":"correct horse"}'
# {"id":1,"email":"ann@example.com","name":"Ann","createdAt":"2026-12-03T11:30:20.937Z"}
curl -X POST localhost:3000/sessions \
-H 'Content-Type: application/json' \
-d '{"email":"ann@example.com","password":"correct horse"}'
# {"token":"0f8e6d3a-…"}
TOKEN=0f8e6d3a-… # paste the token from the previous answer
curl -X POST localhost:3000/notes \
-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"title":"Groceries"}'
# {"id":1,"title":"Groceries","body":"","pinned":false,"createdAt":"…","updatedAt":"…"}
curl "localhost:3000/notes?pinned=false&limit=5" -H "Authorization: Bearer $TOKEN"
# {"page":1,"items":[{"id":1,"title":"Groceries",…}]}The new note got its body and pinned from the schema's defaults, and the query string's 'false' and '5' arrived as a boolean and a number.
6. Test it
Hono apps answer requests without a server through app.request, and every test gets a fresh in-memory database. Create src/app.test.ts:
import { beforeEach, describe, expect, test } from 'bun:test'
import { createApp } from './app'
import { createStore, openDatabase } from './db'
let app: ReturnType<typeof createApp>
beforeEach(() => {
app = createApp(createStore(openDatabase(':memory:')))
})
function send(method: string, path: string, body?: unknown, token?: string) {
return app.request(path, {
method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
})
}
async function signUp(email = 'ann@example.com') {
await send('POST', '/users', { email, name: 'Ann', password: 'correct horse' })
const response = await send('POST', '/sessions', { email, password: 'correct horse' })
const { token } = await response.json() as { token: string }
return token
}
describe('users', () => {
test('sign-up returns the user without the password', async () => {
const response = await send('POST', '/users', {
id: 999, // read-only: dropped, never stored
email: 'ann@example.com',
name: 'Ann',
password: 'correct horse',
})
expect(response.status).toBe(201)
const user = await response.json()
expect(user).toEqual({ id: 1, email: 'ann@example.com', name: 'Ann', createdAt: expect.any(String) })
})
test('invalid input is answered with one issue per field', async () => {
const response = await send('POST', '/users', { email: 'not-an-email', password: 'short' })
expect(response.status).toBe(400)
const { issues } = await response.json() as { issues: { path: (string | number)[], keyword: string }[] }
expect(issues.map(issue => [issue.path.join('.'), issue.keyword])).toEqual([
['name', 'required'],
['email', 'format'],
['password', 'minLength'],
])
})
test('a body that is not JSON is the client\'s error', async () => {
const response = await app.request('/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: 'not json',
})
expect(response.status).toBe(400)
expect(await response.json()).toEqual({ error: 'Malformed JSON in request body' })
})
test('an email registers once', async () => {
await signUp()
const response = await send('POST', '/users', { email: 'ann@example.com', name: 'Ann', password: 'another one' })
expect(response.status).toBe(409)
})
test('a wrong password does not sign in', async () => {
await signUp()
const response = await send('POST', '/sessions', { email: 'ann@example.com', password: 'wrong password' })
expect(response.status).toBe(401)
})
})
describe('notes', () => {
test('need a session', async () => {
expect((await send('GET', '/notes')).status).toBe(401)
})
test('get their defaults on create', async () => {
const token = await signUp()
const response = await send('POST', '/notes', { title: 'Groceries' }, token)
expect(response.status).toBe(201)
expect(await response.json()).toMatchObject({ id: 1, title: 'Groceries', body: '', pinned: false })
})
test('PATCH changes only the fields it sends', async () => {
const token = await signUp()
await send('POST', '/notes', { title: 'Groceries', body: 'milk', pinned: true }, token)
const response = await send('PATCH', '/notes/1', { title: 'Shopping' }, token)
expect(await response.json()).toMatchObject({ title: 'Shopping', body: 'milk', pinned: true })
})
test('query strings are coerced and defaulted', async () => {
const token = await signUp()
await send('POST', '/notes', { title: 'a', pinned: true }, token)
await send('POST', '/notes', { title: 'b' }, token)
const response = await send('GET', '/notes?pinned=true', undefined, token)
const { page, items } = await response.json() as { page: number, items: unknown[] }
expect(page).toBe(1)
expect(items).toEqual([expect.objectContaining({ id: 1, title: 'a', createdAt: expect.any(String) })])
expect((await send('GET', '/notes?page=0', undefined, token)).status).toBe(400)
})
test('are private to their owner', async () => {
const ann = await signUp('ann@example.com')
const bob = await signUp('bob@example.com')
await send('POST', '/notes', { title: 'secret' }, ann)
expect((await send('GET', '/notes/1', undefined, bob)).status).toBe(404)
})
})bun testThe tests check behaviour the schemas are responsible for: the read-only id a client sends is dropped, the password never comes back, the issues point at the right fields, the query string is converted, and a PATCH leaves the fields it didn't send alone. Matching issues by path and keyword rather than by message keeps the tests stable if the wording changes.
7. Publish an OpenAPI document
Each schema can describe itself as JSON Schema through ~standard.jsonSchema (see JSON Schema & OpenAPI): input() for what a request may contain and output() for what a response always contains. That is enough to write the OpenAPI document by hand, from the same schemas the routes validate with. Create src/openapi.ts:
import type { StandardProps } from 'typebox-standard-schema'
import { Type } from 'typebox-standard-schema'
import { Credentials, NewNote, NewUser, NoteId, NotePage, NotePatch, NoteSearch, NoteView, PublicUser } from './schemas'
// Any schema built with Type: what it needs from one is its ~standard.
type Schema = { '~standard': StandardProps }
const target = 'openapi-3.0'
function body(schema: Schema) {
return {
required: true,
content: { 'application/json': { schema: schema['~standard'].jsonSchema.input({ target }) } },
}
}
function reply(description: string, schema?: Schema) {
return {
description,
...(schema && { content: { 'application/json': { schema: schema['~standard'].jsonSchema.output({ target }) } } }),
}
}
// Query and path parameters: one entry per property of an object schema.
function parameters(where: 'query' | 'path', schema: Schema) {
const { properties, required = [] } = schema['~standard'].jsonSchema.input({ target }) as {
properties: Record<string, object>
required?: string[]
}
return Object.entries(properties).map(([name, property]) => ({
name,
in: where,
required: where === 'path' || required.includes(name),
schema: property,
}))
}
const Token = Type.Object({ token: Type.String() })
const signedIn = [{ bearer: [] }]
const id = parameters('path', NoteId)
export const openapi = {
openapi: '3.0.3',
info: { title: 'Notes API', version: '1.0.0' },
components: { securitySchemes: { bearer: { type: 'http', scheme: 'bearer' } } },
paths: {
'/users': {
post: { requestBody: body(NewUser), responses: { 201: reply('Created', PublicUser), 400: reply('Invalid input'), 409: reply('Email taken') } },
},
'/sessions': {
post: { requestBody: body(Credentials), responses: { 201: reply('Signed in', Token), 401: reply('Wrong email or password') } },
delete: { security: signedIn, responses: { 204: reply('Signed out') } },
},
'/me': {
get: { security: signedIn, responses: { 200: reply('The signed-in user', PublicUser) } },
},
'/notes': {
get: { security: signedIn, parameters: parameters('query', NoteSearch), responses: { 200: reply('A page of notes', NotePage) } },
post: { security: signedIn, requestBody: body(NewNote), responses: { 201: reply('Created', NoteView), 400: reply('Invalid input') } },
},
'/notes/{id}': {
get: { security: signedIn, parameters: id, responses: { 200: reply('The note', NoteView), 404: reply('No such note') } },
patch: { security: signedIn, parameters: id, requestBody: body(NotePatch), responses: { 200: reply('Updated', NoteView), 404: reply('No such note') } },
delete: { security: signedIn, parameters: id, responses: { 204: reply('Deleted'), 404: reply('No such note') } },
},
},
}Then serve it from src/app.ts: import it next to the other imports, and add a route before POST /users:
import { openapi } from './openapi'
// inside createApp, before app.post('/users', ...):
app.get('/openapi.json', c => c.json(openapi))With --watch running, localhost:3000/openapi.json serves it at once. The request body of POST /users comes out with password and without id; the response with id and without password. The document validates as OpenAPI 3.0, and any viewer (Swagger UI, Scalar, Redoc) can render it. Schema types the helpers' argument as "anything with ~standard", which every schema built with Type is.
8. Deploy
Bun can compile the whole app into one executable that needs nothing else on the server:
bun build --compile --minify src/index.ts --outfile notes-api
mkdir -p data
PORT=8080 DATABASE_PATH=data/notes.sqlite ./notes-apiSQLite creates the database file but not the folder it goes in: the folder in DATABASE_PATH must exist and be writable by the user that runs the server.
Or package it as a container. Stop the development server from step 5 first (Ctrl+C): the container publishes port 3000 too. Create Dockerfile:
FROM oven/bun:1
WORKDIR /app
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile --production
COPY src ./src
RUN mkdir /data && chown bun:bun /data
USER bun
ENV DATABASE_PATH=/data/notes.sqlite
VOLUME /data
EXPOSE 3000
CMD ["bun", "src/index.ts"]and .dockerignore, which keeps local files and the tests out of the image:
node_modules
notes.sqlite*
notes-api
src/*.test.tsdocker build -t notes-api .
docker run -p 3000:3000 -v notes-data:/data notes-apiThe database lives in the notes-data volume, so it survives a new image. Ctrl+C or docker stop shuts the server down cleanly, thanks to the signal handling in src/index.ts. Put the API behind a reverse proxy that terminates HTTPS: tokens travel in a header.
Where to go next
- Projections: named projections for documentation generators and nesting projections; Validation has how marks work in unions and nested objects.
- Validation: every step of the pipeline, the issue format, and
parse. - Custom formats and checks: your own string formats, and
Type.Refinefor rules that compare fields. - Hono: more on validating Hono routes, and
hono-openapias an alternative to writing the OpenAPI document by hand. - Framework integrations: the same schemas in tRPC, Elysia, SvelteKit, TanStack Form and React Hook Form.