Skip to main content

APIs · Beginner · 22 min

How to Build a REST API with Express 5

By Padding · Updated 15 Nov 2026
Express 5.3 · Node.js 26

You will build a small items API with Express 5.3 on Node.js 26 that validates its input, returns the right HTTP status codes, never sends a stack trace to callers, and has automated tests that use only Node's built-in test runner.

On this page

A REST API lets other programs read and change your data over HTTP: GET to read, POST to create, PUT to replace and DELETE to remove. Express is the long-standing web framework for Node.js, and version 5 is the current major release. It forwards errors from async handlers to your error handler by itself, which version 4 did not, and it has stricter route-path syntax.

This tutorial builds an items API in a few small files. The focus is on what goes wrong: input that does not fit, an item that does not exist, a body that is not JSON, and a bug in your own code. Each gets the correct status code and a short message that tells the caller what to fix and nothing about your server. Data lives in memory, so restarting the server clears it. To run against a real database, see the tutorials on PostgreSQL.

Step 1 · Create the project and install Express

Make a folder, create package.json, and install Express. type: module lets you write import instead of require. The version range ~5.3.0 allows patch releases of 5.3 only:

Bash
mkdir -p ~/items-api
cd ~/items-api
npm init -y
npm pkg set type=module
npm install express@~5.3.0

Check it worked

Bash
node --version
npm ls express

node --version prints v26. and a patch number. npm ls express lists express@5.3.0, or a later 5.3 patch release.

Step 2 · Write the app

The API is split into two files: app.js builds the Express app and server.js starts listening. Keeping them apart lets the tests use the app without starting a server on a fixed port. Create app.js:

Bash
cat > app.js <<'JS'
import express from 'express'

export const app = express()
app.disable('x-powered-by')
app.use(express.json({ limit: '10kb' }))

const items = new Map()
let nextId = 1

export function resetStore() {
  items.clear()
  nextId = 1
}

function parseId(value) {
  if (!/^[1-9]\d*$/.test(value)) return null
  const id = Number(value)
  return Number.isSafeInteger(id) ? id : null
}

function checkItem(body) {
  if (body === null || typeof body !== 'object' || Array.isArray(body)) {
    return { errors: [{ field: 'body', message: 'must be a JSON object' }] }
  }
  const errors = []
  for (const key of Object.keys(body)) {
    if (key !== 'title' && key !== 'done') {
      errors.push({ field: key, message: 'unknown field' })
    }
  }
  const title = typeof body.title === 'string' ? body.title.trim() : body.title
  if (typeof title !== 'string' || title.length < 1 || title.length > 100) {
    errors.push({ field: 'title', message: 'must be a string of 1 to 100 characters' })
  }
  if (body.done !== undefined && typeof body.done !== 'boolean') {
    errors.push({ field: 'done', message: 'must be true or false' })
  }
  if (errors.length > 0) return { errors }
  return { value: { title, done: body.done ?? false } }
}

function invalid(res, errors) {
  return res.status(422).json({ errors })
}

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' })
})

app.get('/api/items', (req, res) => {
  const limit = req.query.limit === undefined ? 20 : Number(req.query.limit)
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
    return invalid(res, [{ field: 'limit', message: 'must be a whole number from 1 to 100' }])
  }
  let list = [...items.values()]
  if (req.query.done !== undefined) {
    if (req.query.done !== 'true' && req.query.done !== 'false') {
      return invalid(res, [{ field: 'done', message: 'must be true or false' }])
    }
    list = list.filter((item) => item.done === (req.query.done === 'true'))
  }
  res.json(list.slice(0, limit))
})

app.post('/api/items', (req, res) => {
  const { value, errors } = checkItem(req.body)
  if (errors) return invalid(res, errors)
  const item = { id: nextId++, ...value }
  items.set(item.id, item)
  res.status(201).location(`/api/items/${item.id}`).json(item)
})

app.get('/api/items/:id', (req, res) => {
  const id = parseId(req.params.id)
  if (id === null) return invalid(res, [{ field: 'id', message: 'must be a positive whole number' }])
  const item = items.get(id)
  if (!item) return res.status(404).json({ error: 'Item not found' })
  res.json(item)
})

app.put('/api/items/:id', (req, res) => {
  const id = parseId(req.params.id)
  if (id === null) return invalid(res, [{ field: 'id', message: 'must be a positive whole number' }])
  if (!items.has(id)) return res.status(404).json({ error: 'Item not found' })
  const { value, errors } = checkItem(req.body)
  if (errors) return invalid(res, errors)
  const item = { id, ...value }
  items.set(id, item)
  res.json(item)
})

app.delete('/api/items/:id', (req, res) => {
  const id = parseId(req.params.id)
  if (id === null) return invalid(res, [{ field: 'id', message: 'must be a positive whole number' }])
  if (!items.delete(id)) return res.status(404).json({ error: 'Item not found' })
  res.status(204).end()
})

app.use((req, res) => {
  res.status(404).json({ error: 'Not found' })
})

export function errorHandler(err, req, res, next) {
  if (res.headersSent) return next(err)
  if (err.type === 'entity.parse.failed') {
    return res.status(400).json({ error: 'Body is not valid JSON' })
  }
  if (err.type === 'entity.too.large') {
    return res.status(413).json({ error: 'Body is too large' })
  }
  console.error(err)
  res.status(500).json({ error: 'Internal server error' })
}

app.use(errorHandler)
JS

Read it from the top:

  • express.json({ limit: '10kb' }) parses JSON request bodies and refuses ones over 10 kilobytes. In Express 5, req.body stays undefined when no body was parsed, for instance when the client sends no Content-Type: application/json, so checkItem treats that as "not an object".
  • app.disable('x-powered-by') stops Express from announcing itself in every response header.
  • checkItem is the validation. It rejects unknown fields, requires a trimmed title of 1 to 100 characters, and requires done to be a boolean when given. It returns every problem at once, so the caller can fix them in one go.
  • Validation failures give 422, a missing item gives 404, and a new item gives 201 with a Location header. A delete gives 204 with no body.
  • The last two app.use calls matter. The first catches any URL that no route matched and returns a JSON 404. The second is the error handler. Express recognises an error handler by its four parameters, so keep all four even though next is sometimes unused. It maps the body parser's errors to 400 and 413, and answers anything else with a fixed message. It writes the real error to the server's log with console.error.

Now create server.js:

Bash
cat > server.js <<'JS'
import { app } from './app.js'

const port = Number(process.env.PORT ?? 8000)

const server = app.listen(port, '127.0.0.1', (error) => {
  if (error) throw error
  console.log(`Listening on http://127.0.0.1:${port}`)
})

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.on(signal, () => server.close(() => process.exit(0)))
}
JS

It listens on 127.0.0.1, so only your own computer can reach it while you develop, and it stops cleanly on Ctrl+C. Start it in a second terminal. --watch restarts it when you change a file:

Bash
cd ~/items-api
node --watch server.js

Check it worked

Express's JSON has no newline at the end, so -w '\n' makes curl add one, which keeps your prompt on its own line:

Bash
curl -s -w '\n' http://127.0.0.1:8000/api/health

The output is {"status":"ok"}.

Step 3 · Create and read items

Create two items. --json sets the content type for you, and -i shows the status line and headers:

Bash
curl -si -w '\n' --json '{"title": "Learn Express"}' http://127.0.0.1:8000/api/items
curl -s -w '\n' --json '{"title": "Write tests", "done": true}' http://127.0.0.1:8000/api/items

The first response starts with HTTP/1.1 201 Created and has Location: /api/items/1. Its body is {"id":1,"title":"Learn Express","done":false}. There is no X-Powered-By header. Read the items back:

Bash
curl -s -w '\n' http://127.0.0.1:8000/api/items
curl -s -w '\n' http://127.0.0.1:8000/api/items/1
curl -s -w '\n' 'http://127.0.0.1:8000/api/items?done=true'

The first prints both items. The second prints item 1. The third prints only item 2.

Check it worked

Bash
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/items/2

The output is 200.

Step 4 · Replace and delete

Bash
curl -s -w '\n' -X PUT --json '{"title": "Learn Express 5", "done": true}' http://127.0.0.1:8000/api/items/1
curl -si -w '\n' -X DELETE http://127.0.0.1:8000/api/items/2
curl -s -w '\n' http://127.0.0.1:8000/api/items/2

The PUT returns the replaced item. The delete answers HTTP/1.1 204 No Content and the next request gets 404 with {"error":"Item not found"}.

Step 5 · Check that bad input is rejected

Send input that is wrong in different ways:

Bash
curl -s -w '\n%{http_code}\n' --json '{"title": ""}' http://127.0.0.1:8000/api/items
curl -s -w '\n%{http_code}\n' --json '{"titel": "typo"}' http://127.0.0.1:8000/api/items
curl -s -w '\n%{http_code}\n' --json '[1, 2]' http://127.0.0.1:8000/api/items
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/api/items/abc
curl -s -w '\n%{http_code}\n' 'http://127.0.0.1:8000/api/items?limit=1000'
curl -s -w '\n%{http_code}\n' --json '{not json' http://127.0.0.1:8000/api/items
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/no/such/route

The first five answer 422 with an errors list that names the field and says what is wrong, such as {"errors":[{"field":"title","message":"must be a string of 1 to 100 characters"}]}. The typo case reports the unknown field titel and the missing title together. The body that is not JSON answers 400 with {"error":"Body is not valid JSON"}, and the unknown route answers 404 with {"error":"Not found"}. Check that the size limit works too. This sends a body of about 20 kilobytes:

Bash
head -c 20000 /dev/zero | tr '\0' 'a' > big.txt
(printf '{"title": "'; cat big.txt; printf '"}') > big.json
curl -s -w '\n%{http_code}\n' --json @big.json http://127.0.0.1:8000/api/items
rm big.txt big.json

The output is {"error":"Body is too large"} and 413.

Check it worked

Bash
curl -s -o /dev/null -w '%{http_code}\n' --json '{"title": "   "}' http://127.0.0.1:8000/api/items

The output is 422, because a title of only spaces is empty once it is trimmed.

Step 6 · Keep stack traces away from callers

When your own code throws, the caller must not receive the stack trace. It names your files and your dependencies, which helps an attacker. Express's built-in error handler shows the stack in the response unless NODE_ENV is production. You can see that with a throwaway server that has a deliberate bug and no error handler of its own. Create crash.js:

Bash
cat > crash.js <<'JS'
import express from 'express'

const app = express()

app.get('/crash', async () => {
  const secretTotal = 0
  throw new Error(`cannot divide by ${secretTotal}`)
})

app.listen(8001, '127.0.0.1')
JS

The handler is async on purpose. Express 5 catches the rejected promise and passes the error on, where Express 4 would have left the request hanging. Run it, and call it:

Bash
node crash.js
Bash
curl -s http://127.0.0.1:8001/crash

The response is an HTML page with Error: cannot divide by 0 and the lines of the stack trace, each starting at, with file paths. That is what the default handler hands out when NODE_ENV is not production. Stop it with Ctrl+C, then change crash.js to use your handler from app.js. This version writes the file again from scratch:

Bash
cat > crash.js <<'JS'
import express from 'express'
import { errorHandler } from './app.js'

const app = express()

app.get('/crash', async () => {
  const secretTotal = 0
  throw new Error(`cannot divide by ${secretTotal}`)
})

app.use(errorHandler)

app.listen(8001, '127.0.0.1')
JS
Bash
node crash.js
Bash
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8001/crash

The output is {"error":"Internal server error"} and 500. The trace is in the terminal that runs crash.js, where only you can read it. The same applies when you set NODE_ENV=production on a real deployment, but do not depend on that setting alone: register your own handler, as app.js does.

Stop it with Ctrl+C and delete the file:

Bash
rm crash.js

Step 7 · Write automated tests

Node has a test runner built in, so you need no extra packages. node:test runs the files, node:assert checks the results, and Node's built-in fetch calls the app. The tests start the app on a random free port, so they never clash with your running server:

Bash
mkdir -p test
cat > test/items.test.js <<'JS'
import assert from 'node:assert/strict'
import { after, beforeEach, test } from 'node:test'
import { app, resetStore } from '../app.js'

const server = app.listen(0, '127.0.0.1')
await new Promise((resolve) => server.once('listening', resolve))
const base = `http://127.0.0.1:${server.address().port}`

after(() => {
  server.close()
  server.closeAllConnections()
})
beforeEach(() => resetStore())

const send = (path, method, body) =>
  fetch(base + path, {
    method,
    headers: { 'content-type': 'application/json' },
    body: typeof body === 'string' ? body : JSON.stringify(body),
  })

test('creates and reads an item', async () => {
  const created = await send('/api/items', 'POST', { title: 'Learn Express' })
  assert.equal(created.status, 201)
  assert.equal(created.headers.get('location'), '/api/items/1')
  const item = await created.json()
  assert.deepEqual(item, { id: 1, title: 'Learn Express', done: false })
  const fetched = await fetch(`${base}/api/items/1`)
  assert.deepEqual(await fetched.json(), item)
})

test('a missing item is a 404', async () => {
  const response = await fetch(`${base}/api/items/99`)
  assert.equal(response.status, 404)
  assert.deepEqual(await response.json(), { error: 'Item not found' })
})

test('bad input is a 422', async () => {
  for (const body of [{ title: '' }, { title: '   ' }, { titel: 'typo' }, { title: 'x'.repeat(101) }, {}, [1]]) {
    const response = await send('/api/items', 'POST', body)
    assert.equal(response.status, 422, JSON.stringify(body))
  }
})

test('a body that is not JSON is a 400', async () => {
  const response = await send('/api/items', 'POST', '{not json')
  assert.equal(response.status, 400)
  assert.deepEqual(await response.json(), { error: 'Body is not valid JSON' })
})

test('a delete is a 204, then a 404', async () => {
  await send('/api/items', 'POST', { title: 'Temporary' })
  assert.equal((await send('/api/items/1', 'DELETE')).status, 204)
  assert.equal((await send('/api/items/1', 'DELETE')).status, 404)
})

test('filters by done', async () => {
  await send('/api/items', 'POST', { title: 'One' })
  await send('/api/items', 'POST', { title: 'Two', done: true })
  const response = await fetch(`${base}/api/items?done=true`)
  assert.deepEqual((await response.json()).map((item) => item.title), ['Two'])
})
JS
npm pkg set scripts.test="node --test"
npm test

beforeEach empties the store, so tests do not depend on each other. The output lists each test with a check mark and ends with a summary: tests 6, pass 6 and fail 0.

Troubleshooting

  • Error: listen EADDRINUSE: address already in use 127.0.0.1:8000 means another process uses the port. Stop it, or run PORT=8010 node server.js.
  • curl shows {"errors":[{"field":"body","message":"must be a JSON object"}]} for a body that looks right. The request has no Content-Type: application/json header, so Express did not parse it. Use --json, or add the header.
  • Express 4 habits that fail in 5: a route path such as /files/* is now an error. Name the wildcard, /files/*splat. req.body is undefined without a parser. Optional parameters use braces, /:id{/:format}, not a trailing ?.
  • A test never finishes. A server that is still open keeps Node alive. Close it in after, as the test file does.

Step 8 · Run it for real

For other people to use the API, run node server.js as a service behind a reverse proxy that handles HTTPS. To accept connections from outside the machine, change the 127.0.0.1 in server.js to 0.0.0.0 only when something in front of it controls access. Set NODE_ENV=production in the service's environment, which turns off the slower development behaviour in Express and its dependencies. See run your app as a systemd service and nginx as a reverse proxy for a Node app. An API open to the internet also needs authentication and rate limiting, which this tutorial does not cover.

Step 9 · Stop the server and clean up

Press Ctrl+C in the server terminal. Then delete the project folder, which holds only what you made here:

Bash
cd ~
rm -rf ~/items-api

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.