Xenors Code Lab
Node.js Tutorial

Express.js Tutorial for Beginners: Build a REST API

Build your first Express 5 REST API with Node.js, including GET and POST routes, JSON validation, error middleware and predictable 200, 201, 400 and 404 responses.

By Ashok Kumar Yadav - October 12, 2026 · Updated November 21, 2026

Express.js tutorial illustration for Node.js REST API routing

What is Express.js? A working Node.js API tutorial

Express.js is a Node.js framework for routing HTTP requests through middleware and handlers. For example, a GET /api/tasks request can return JSON, while a POST /api/tasks request validates input before creating a record. Express builds on Node.js; it is not the same as the native node:http module.

To use Express.js, install it with npm, create an app, add middleware such as express.json(), define routes and run app.listen(). This guide replaces a bare Node.js HTTP demo with a reproducible Express 5 task API, covering successful and failed requests.

Version: Express 5 requires Node.js 18 or newer according to the official installation guide. The application here is a teaching demo; it does not include durable storage or authentication.

How the Express request lifecycle works

Express executes matching middleware in registration order. Middleware can read or modify req and res, finish with res.json(), or call next(). If middleware neither sends a response nor calls next(), a request can hang. Always register the JSON parser before handlers that read JSON bodies.

Express featureWhat it doesExample
app.use()Runs middlewareParse JSON before routes
app.get()Reads a resourceGET /api/tasks
app.post()Creates a resourcePOST /api/tasks
req.paramsReads URL segmentsTask ID from /api/tasks/1
res.status().json()Sends a JSON HTTP response400, 404 or 201

Step 1: Install Express 5

With Node.js 18+ installed, open a terminal:

mkdir express-api-lab
cd express-api-lab
npm init -y
npm install express@5
# Save the next example as app.mjs
node app.mjs

Using app.mjs lets this example use standard ES-module import without modifying package.json. Keep the process running at http://localhost:3000.

Step 2: Complete Express.js REST API example

Paste the full script below into app.mjs. It implements a health check, a task collection, input validation, a task-by-ID lookup, structured 404 handling and JSON parse-error handling. The collection is intentionally in memory so you can learn the HTTP contract before using a database.

import express from 'express';

const app = express();
app.use(express.json({ limit: '16kb' }));
const tasks = new Map(); // Demo only; resets after restart
let nextId = 1;

app.get('/health', (req, res) => res.json({ ok: true }));
app.get('/api/tasks', (req, res) => {
  res.json({ tasks: [...tasks.values()] });
});
app.post('/api/tasks', (req, res) => {
  const title = req.body?.title;
  if (typeof title !== 'string' || title.trim().length < 3 || title.length > 120) {
    return res.status(400).json({ error: 'title must be 3-120 characters' });
  }
  const task = { id: nextId++, title: title.trim(), completed: false };
  tasks.set(task.id, task);
  res.status(201).location('/api/tasks/' + task.id).json(task);
});
app.get('/api/tasks/:id', (req, res) => {
  const id = Number(req.params.id);
  if (!Number.isSafeInteger(id) || id < 1) {
    return res.status(400).json({ error: 'invalid task id' });
  }
  const task = tasks.get(id);
  if (!task) return res.status(404).json({ error: 'task not found' });
  res.json(task);
});
app.use((req, res) => res.status(404).json({ error: 'route not found' }));
app.use((err, req, res, next) => {
  if (err.type === 'entity.parse.failed') {
    return res.status(400).json({ error: 'invalid JSON' });
  }
  console.error(err);
  res.status(500).json({ error: 'internal server error' });
});
const port = Number(process.env.PORT || 3000);
app.listen(port, () => console.log('API listening on port ' + port));

Data persistence limitation: Map clears whenever the process restarts, and the numeric ID is not suitable for a multi-instance deployment. Use a database, authentication and authorization in production.

Step 3: Test real HTTP status codes with curl

In a second terminal, run these bash-style commands. On Windows PowerShell, use curl.exe and adjust quoting for the shell. The listed statuses are expected results, not claims from a deployed instance.

curl -i http://localhost:3000/api/tasks
curl -i -X POST http://localhost:3000/api/tasks \
  -H "Content-Type: application/json" \
  -d '{"title":"Check camera alert"}'
curl -i http://localhost:3000/api/tasks/1
curl -i http://localhost:3000/api/tasks/999
curl -i -X POST http://localhost:3000/api/tasks \
  -H "Content-Type: application/json" \
  -d '{"title":"x"}'
ScenarioExpected responseReason
GET task list200 and a tasks arrayCollection exists
POST valid title201, JSON task and LocationResource created
GET existing ID200 and saved taskResource found
POST short title400 with validation errorBad request
GET missing ID404Resource absent
GET invalid ID such as abc400Invalid path parameter
Malformed JSON body400JSON parser failure

For client-side JavaScript requests, follow the Fetch API tutorial and inspect request methods, status codes and headers in DevTools Network.

Six common Express.js mistakes and how to debug them

  1. Using native HTTP for an Express tutorial: http.createServer demonstrates Node.js, not Express routes. Use import express from 'express'.
  2. Missing JSON middleware: register app.use(express.json()) before any POST routes that read req.body.
  3. Wrong HTTP statuses: 201 means created, 400 means invalid input, 404 means missing resource and 500 means an internal error.
  4. Wrong request property: req.params reads path variables, req.query query strings and req.body parsed request payloads.
  5. 404 handler registered before routes: keep the catch-all after valid routes or it can intercept intended requests.
  6. Mixing Express 4 and 5 async examples: Express 5 automatically forwards rejected promises returned by handlers to the error handler, whereas Express 4 requires manual forwarding; check the official migration guide.

Before changing application logic, make sure your Node process is running and that port 3000 is available. “Connection refused” means the HTTP request never reached Express.

Before deploying this Express API

Add durable database storage, authentication, authorization, rate limiting, request validation, HTTPS, structured logs, an explicit request timeout and controlled CORS if a browser frontend uses a separate origin. Never commit API keys or expose raw exception stacks. Avoid treating a 200 response as proof that the data was persisted or the user was authorized.

For a Python comparison, see Xenors' FastAPI and Docker deployment tutorial. Explore the Node.js learning hub for the runtime concepts underlying Express.

Practice challenge: implement PATCH safely

Add PATCH /api/tasks/:id with a completed boolean. Return 400 if it is not a boolean, 404 if no task exists and 200 after an update. Confirm that invalid requests leave stored data unchanged by calling the GET route again. Document your observed HTTP codes and error payloads.

Frequently asked Express.js questions

How do I build an API using Express.js?

Install Express, create an app, parse JSON, register GET and POST routes, return meaningful status codes, handle errors and start the Node process. The full working example above follows this flow.

What is the difference between Node.js and Express.js?

Node.js executes server-side JavaScript. Express provides a higher-level interface for HTTP routing and middleware on top of Node.js.

Does Express 5 handle async errors automatically?

Yes. Promise rejections returned by route handlers are forwarded to error middleware in Express 5. Review Express's official error handling documentation.

Primary technical sources

Checked November 21, 2026: Installing Express, Hello World, Using Middleware, Error Handling and Express 5 Migration. These are the authoritative references for version-specific behavior.