Thuta Learning
Node.js
ProjectsWeb DevelopmentBeginner

Mini Project: User API

Node.jsLesson 2645 min

What you'll walk away with

  • Group all routes of one resource in an express.Router() and mount it at /api/users
  • Use router.param() to check :id and load the user once for every route
  • Share one validation function between POST and PATCH with a partial mode
  • Answer DELETE with 204 No Content and place the app-level 404 and error handler in the right order

Explain it simply

Explain it simply

Over the last four lessons you built the parts one at a time: the contract, the list route, the item route and the create route. This mini project joins them into one app and adds the two missing operations, update (PATCH) and delete (DELETE). That completes all four CRUD operations: Create, Read, Update, Delete.

It is like finishing a house. The rooms (routes) already exist; the last step is deciding how they are arranged, who guards the entrance (middleware) and how someone who walks into the wrong door is shown the way out (the 404 and the error handler).

Problem → Why → Solution

The problem: a file that grows by copy and paste

Adding PATCH and DELETE the quick way means copying the id-checking code into three routes. Soon GET has the 400 check but DELETE forgot it, and PATCH skips validation and runs Object.assign(user, req.body), which even lets a client change the id.

Order is the other trap. Put the 404 fallback above the routes by mistake and every request gets a 404; the routes are never reached.

crud-draft.js
app.use((req, res) => res.status(404).json({ error: 'Not found' })); // too early!

app.patch('/api/users/:id', (req, res) => {
  const user = users.find((u) => u.id === Number(req.params.id));
  if (!user) return res.status(404).json({ error: 'User not found' });
  Object.assign(user, req.body);          // no validation; { "id": 99 } works too
  res.json(user);
});

app.delete('/api/users/:id', (req, res) => {
  users = users.filter((u) => u.id !== Number(req.params.id)); // no 404 check
  res.json({ message: 'deleted' });
});

Why this happens

When one piece of logic lives in many places, every fix has to be remembered in all of them. And Express tries middleware strictly in the order it was added; the first one that sends a response wins.

Core concept: arrange the app in three layers

Even inside a single file, thinking of the code as three layers makes it easy to split into files once the project grows.

1. The data layer

The users array, nextId and validateUser() live here. validateUser(body, partial) requires every field for POST (partial = false) and checks only the fields that were sent for PATCH (partial = true). With the rules in one place, POST and PATCH can never drift apart.

2. The router layer

express.Router() is like a small app. Routes are written with relative paths such as '/' and '/:id', and app.use('/api/users', router) adds the prefix in one place. router.param('id', ...) runs once before any route with :id and either answers 400 or 404 or prepares res.locals.user.

3. The app layer

Order matters: express.json() first, then the router, then the 404 fallback, and finally the four-parameter error handler. The error handler catches anything a route throws (and, in Express 5, any rejected async handler) and turns it into a JSON 500.

RouteSuccessErrors
GET /api/users200 { count, data }400 (bad role)
GET /api/users/:id200 { data }400, 404
POST /api/users201 { data } + Location400
PATCH /api/users/:id200 { data }400, 404
DELETE /api/users/:id204 (no body)400, 404

This project uses PATCH rather than PUT. PUT means "replace the whole item with this body", so the client must send every field and any field it leaves out should disappear. PATCH means "change only the fields I sent", which fits an admin screen that just changes a role. That is exactly why PATCH calls validateUser() in partial mode.

Mental model: one request's journey
  1. express.json() parses the body
  2. Router matches path and method
  3. router.param loads the user
  4. Handler sends a 2xx or a 4xx
  5. No match: 404; a throw: 500

Every request travels this path from top to bottom and stops wherever a response is sent.

General pattern

javascript
const router = express.Router();
router.param('id', (req, res, next, raw) => { /* 400 / 404 or next() */ });
router.get('/', list);        router.post('/', create);
router.get('/:id', readOne);  router.patch('/:id', update);
router.delete('/:id', remove);                  // 204, no body

app.use(express.json());
app.use('/api/things', router);
app.use(notFoundHandler);                       // (req, res)
app.use(errorHandler);                          // (err, req, res, next)

One router per resource, one router.param for the :id logic, and in the app: body parser, router, 404, error handler, in that order.

The complete User API

Four comment lines divide the code into data, routes, app and a client session. At the bottom, a call() helper sends one request and prints the method, path, status and body on a single line. The session runs seven steps: create a user, update it, try an invalid update, delete another user, look for the deleted one, filter, and call a route that does not exist.

user-api.js
const express = require('express');

// ---------- data: the only code that touches the array ----------
const ROLES = ['admin', 'member'];
const users = [
  { id: 1, name: 'Aung Aung', role: 'admin' },
  { id: 2, name: 'Mya Mya', role: 'member' },
  { id: 3, name: 'Zaw Zaw', role: 'member' },
];
let nextId = 4;

// partial = true for PATCH: only check the fields that were sent
function validateUser(body, partial) {
  const errors = [];
  const value = {};
  if (!partial || body.name !== undefined) {
    const name = typeof body.name === 'string' ? body.name.trim() : '';
    if (name.length < 2 || name.length > 50) errors.push('name must be 2-50 characters');
    else value.name = name;
  }
  if (!partial || body.role !== undefined) {
    const role = body.role ?? 'member';
    if (ROLES.includes(role)) value.role = role;
    else errors.push(`role must be one of: ${ROLES.join(', ')}`);
  }
  return { errors, value };
}

// ---------- routes: everything under /api/users ----------
const router = express.Router();

// Runs before every route that has :id in its path
router.param('id', (req, res, next, raw) => {
  if (!/^[1-9][0-9]*$/.test(raw)) {
    return res.status(400).json({ error: 'id must be a positive whole number' });
  }
  const user = users.find((u) => u.id === Number(raw));
  if (!user) return res.status(404).json({ error: `User ${raw} not found` });
  res.locals.user = user;
  next();
});

router.get('/', (req, res) => {
  const { role } = req.query;
  if (role !== undefined && !ROLES.includes(role)) {
    return res.status(400).json({ error: 'unknown role' });
  }
  const data = role ? users.filter((u) => u.role === role) : users;
  res.json({ count: data.length, data });
});

router.get('/:id', (req, res) => res.json({ data: res.locals.user }));

router.post('/', (req, res) => {
  const { errors, value } = validateUser(req.body ?? {}, false);
  if (errors.length) {
    return res.status(400).json({ error: 'Validation failed', details: errors });
  }
  const user = { id: nextId++, ...value };
  users.push(user);
  res.status(201).location(`/api/users/${user.id}`).json({ data: user });
});

router.patch('/:id', (req, res) => {
  const { errors, value } = validateUser(req.body ?? {}, true);
  if (errors.length) {
    return res.status(400).json({ error: 'Validation failed', details: errors });
  }
  Object.assign(res.locals.user, value);
  res.json({ data: res.locals.user });
});

router.delete('/:id', (req, res) => {
  users.splice(users.indexOf(res.locals.user), 1);
  res.status(204).end();
});

// ---------- app: middleware, router, fallbacks ----------
const app = express();
app.use(express.json());
app.use('/api/users', router);
app.use((req, res) => {
  res.status(404).json({ error: `Cannot ${req.method} ${req.path}` });
});
app.use((err, req, res, next) => {
  if (err.type === 'entity.parse.failed') {
    return res.status(400).json({ error: 'Body is not valid JSON' });
  }
  console.error(err);
  res.status(500).json({ error: 'Internal server error' });
});

// ---------- a scripted client session ----------
const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  async function call(method, path, body) {
    const init = { method };
    if (body) {
      init.headers = { 'Content-Type': 'application/json' };
      init.body = JSON.stringify(body);
    }
    const res = await fetch(base + path, init);
    const text = await res.text();
    console.log(`${method} ${path} -> ${res.status} ${text || '(no body)'}`);
  }

  await call('POST', '/api/users', { name: 'Hla Hla' });
  await call('PATCH', '/api/users/4', { role: 'admin' });
  await call('PATCH', '/api/users/4', { name: ' ' });
  await call('DELETE', '/api/users/2');
  await call('GET', '/api/users/2');
  await call('GET', '/api/users?role=admin');
  await call('GET', '/api/orders');
  server.close();
});

Code breakdown

  1. Partial validationif (!partial || body.name !== undefined) {

    For POST, partial is false, so name is always checked. For PATCH it is checked only when sent, which is why { role: 'admin' } on its own succeeds.

  2. One id check for all routesrouter.param('id', (req, res, next, raw) => {

    This callback runs before GET, PATCH and DELETE on /:id. After user 2 is deleted, GET /api/users/2 gets its 404 right here.

  3. Update in placeObject.assign(res.locals.user, value);

    value holds only validated fields, so the id cannot be changed. res.locals.user is the very object inside the array, so the array sees the change too.

  4. 204 No Contentres.status(204).end();

    A successful delete has nothing to return, so it sends 204 with no body; the output shows (no body).

  5. Mounting the routerapp.use('/api/users', router);

    '/:id' inside the router becomes /api/users/:id. Requests with another prefix, such as /api/orders, skip the router and reach the 404 fallback below.

  6. Last line of defenceapp.use((err, req, res, next) => {

    Express recognises an error handler only by its four parameters. Internal details go to the log with console.error; the client sees only a generic message.

You should see
POST /api/users -> 201 {"data":{"id":4,"name":"Hla Hla","role":"member"}}
PATCH /api/users/4 -> 200 {"data":{"id":4,"name":"Hla Hla","role":"admin"}}
PATCH /api/users/4 -> 400 {"error":"Validation failed","details":["name must be 2-50 characters"]}
DELETE /api/users/2 -> 204 (no body)
GET /api/users/2 -> 404 {"error":"User 2 not found"}
GET /api/users?role=admin -> 200 {"count":2,"data":[{"id":1,"name":"Aung Aung","role":"admin"},{"id":4,"name":"Hla Hla","role":"admin"}]}
GET /api/orders -> 404 {"error":"Cannot GET /api/orders"}

Splitting the project into files

As routes multiply, the comment layers become files. data/users.js exports the array and validateUser, routes/users.js exports the router, app.js wires everything together and exports the app, and server.js contains little more than app.listen(process.env.PORT).

Because app.js exports the app without listening, test files can start it on port 0 themselves and run a session just like the one in this example. Combine that with Node's built-in test runner (node --test) and the session becomes an automated integration test.

text
user-api/
---------
user-api/
  data/users.js     users array, nextId, validateUser()
  routes/users.js   express.Router() + router.param('id')
  app.js            json parser, mount router, 404, error handler
  server.js         app.listen(process.env.PORT || 3000)
  test/api.test.js  start app on port 0, call it with fetch

In real projects

In real projects

This shape is the backbone of admin panels, internal tools and mobile backends. Three things change in production. First, the in-memory array must become a database: data vanishes on every restart, and if two server processes run, each has its own array, so their data disagrees. Second, routes that change data, like PATCH and DELETE, need authentication and authorization; in this project anyone can still delete any user.

Third, when two people edit the same user at once, the later PATCH can silently overwrite the earlier change. Teams prevent this with techniques such as the ETag and If-Match headers, or a version column in the database. None of these changes the contract you built here, which is exactly why designing it first pays off.

Common mistakes

Common mistakes

Calling Object.assign(user, req.body) directly

A client that sends { "id": 1 } gives two users the same id, and new fields such as { "isAdmin": true } slip in as well. This is called a mass assignment vulnerability. Assign only the validated value object.

Putting the 404 fallback above the router

A fallback registered with app.use() matches every path, so above the router it answers every route with 404. The fallback and the error handler always go last.

Sending a body with 204

Writing res.status(204).json({ message: 'deleted' }) does not deliver the message: HTTP says a 204 has no body, so Express drops it and the client never sees it. Use 200 if you want a message, or 204 with end() if you do not.

Best practices

Best practices

  • For every new feature, update the contract table (method, path, status) before writing code
  • Keep the client session script with the project and rerun it after every change to catch regressions at once
  • Log with console.error inside the error handler, but never show a stack trace to the client
  • For a new resource such as orders, create a new router file and just mount it in app.js

Mini challenge

Add a 409 for duplicate names and a /stats route

Add two features to the User API. (1) POST answers 409 Conflict when a user with the same name already exists, ignoring case. (2) GET /api/users/stats returns the total, admin and member counts. Watch the route order.

  • A nameTaken(name, exceptId) helper compares names without caring about case
  • A duplicate name answers 409 with an error naming the duplicate
  • Register the /stats route above the '/:id' route
  • The stats response has the shape { data: { total, admin, member } }
user-api-extra.js
const express = require('express');

const users = [/* TODO: two seed users */];
let nextId = 3;

function nameTaken(name, exceptId) {
  // TODO: true if another user (id !== exceptId) has the same name, any case
}

const router = express.Router();

// TODO: GET /stats -> { data: { total, admin, member } }  (where must it go?)
// TODO: GET /:id
// TODO: POST / -> 400 for a missing name, 409 if nameTaken, else 201

const app = express();
// TODO: json parser + mount the router at /api/users
// TODO: listen on 0; POST 'Kyaw Kyaw', 'mya mya', 'Su Su'; GET /stats; close

Expected: Kyaw Kyaw and Su Su get 201, mya mya gets 409 because Mya Mya exists, and /stats reports total 4, admin 1, member 3.

Show hint

users.some() returns true as soon as one item matches. If /stats sits below '/:id', "stats" is taken as an id and you get a 404.

Show solution
user-api-extra.js
const express = require('express');

const users = [
  { id: 1, name: 'Aung Aung', role: 'admin' },
  { id: 2, name: 'Mya Mya', role: 'member' },
];
let nextId = 3;

// true if another user (not exceptId) already has this name, ignoring case
function nameTaken(name, exceptId) {
  const wanted = name.toLowerCase();
  return users.some((u) => u.id !== exceptId && u.name.toLowerCase() === wanted);
}

const router = express.Router();

// Static path first, or '/:id' would capture "stats"
router.get('/stats', (req, res) => {
  const admin = users.filter((u) => u.role === 'admin').length;
  res.json({ data: { total: users.length, admin, member: users.length - admin } });
});

router.get('/:id', (req, res) => {
  const user = users.find((u) => u.id === Number(req.params.id));
  if (!user) return res.status(404).json({ error: 'User not found' });
  res.json({ data: user });
});

router.post('/', (req, res) => {
  const name = typeof req.body?.name === 'string' ? req.body.name.trim() : '';
  if (name.length < 2) return res.status(400).json({ error: 'name is required' });
  if (nameTaken(name)) {
    return res.status(409).json({ error: `A user named ${name} already exists` });
  }
  const user = { id: nextId++, name, role: 'member' };
  users.push(user);
  res.status(201).json({ data: user });
});

const app = express();
app.use(express.json());
app.use('/api/users', router);

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/api/users`;
  const post = (name) => fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name }),
  });
  for (const name of ['Kyaw Kyaw', 'mya mya', 'Su Su']) {
    const res = await post(name);
    console.log(`POST ${name} ->`, res.status, JSON.stringify(await res.json()));
  }
  const stats = await fetch(`${url}/stats`);
  console.log('GET /stats ->', stats.status, JSON.stringify(await stats.json()));
  server.close();
});

Quick quiz 1 / 3

When the example session finishes, how many users are left in the array?

Quick quiz 2 / 3

If router.get('/:id', ...) is registered above router.get('/stats', ...), what does GET /api/users/stats return (with the example's router.param)?

Quick quiz 3 / 3

What does the example app do with PATCH /api/users/4 and the body { "id": 1, "role": "admin" }?

What to remember

  • Group one resource's routes in an express.Router() and mount it under a prefix
  • router.param() checks the id and loads the user in one place for every :id route
  • POST and PATCH share one validation function and assign only validated fields
  • Order: express.json(), router, 404 fallback, error handler; DELETE answers 204 with no body

Express application generator structure — Express.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project: User API | Thuta Learning