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

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 feature | What it does | Example |
|---|---|---|
app.use() | Runs middleware | Parse JSON before routes |
app.get() | Reads a resource | GET /api/tasks |
app.post() | Creates a resource | POST /api/tasks |
req.params | Reads URL segments | Task ID from /api/tasks/1 |
res.status().json() | Sends a JSON HTTP response | 400, 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"}'
| Scenario | Expected response | Reason |
|---|---|---|
| GET task list | 200 and a tasks array | Collection exists |
| POST valid title | 201, JSON task and Location | Resource created |
| GET existing ID | 200 and saved task | Resource found |
| POST short title | 400 with validation error | Bad request |
| GET missing ID | 404 | Resource absent |
GET invalid ID such as abc | 400 | Invalid path parameter |
| Malformed JSON body | 400 | JSON 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
- Using native HTTP for an Express tutorial:
http.createServerdemonstrates Node.js, not Express routes. Useimport express from 'express'. - Missing JSON middleware: register
app.use(express.json())before any POST routes that readreq.body. - Wrong HTTP statuses: 201 means created, 400 means invalid input, 404 means missing resource and 500 means an internal error.
- Wrong request property:
req.paramsreads path variables,req.queryquery strings andreq.bodyparsed request payloads. - 404 handler registered before routes: keep the catch-all after valid routes or it can intercept intended requests.
- 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.