How to build a REST API with Express.js?
Building a REST API with Express.js
A REST API (Representational State Transfer) uses HTTP methods to perform CRUD operations on resources. Express.js makes this straightforward with its routing system.
HTTP Methods → CRUD
| HTTP Method | CRUD | Description |
|---|---|---|
| GET | Read | Retrieve a resource |
| POST | Create | Create a new resource |
| PUT | Update (full) | Replace a resource |
| PATCH | Update (partial) | Modify a resource |
| DELETE | Delete | Remove a resource |
Complete Users REST API
js
const express = require('express');
const app = express();
app.use(express.json()); // parse JSON request body
// In-memory store (use a database in production)
let users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
];
let nextId = 3;
// GET /users — list all users
app.get('/users', (req, res) => {
res.json(users);
});
// GET /users/:id — get one user
app.get('/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' });
res.json(user);
});
// POST /users — create a user
app.post('/users', (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'name and email are required' });
}
const user = { id: nextId++, name, email };
users.push(user);
res.status(201).json(user);
});
// PUT /users/:id — replace a user
app.put('/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === Number(req.params.id));
if (index === -1) return res.status(404).json({ error: 'User not found' });
users[index] = { id: Number(req.params.id), ...req.body };
res.json(users[index]);
});
// PATCH /users/:id — partially update a user
app.patch('/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);
res.json(user);
});
// DELETE /users/:id — delete a user
app.delete('/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === Number(req.params.id));
if (index === -1) return res.status(404).json({ error: 'User not found' });
users.splice(index, 1);
res.status(204).send();
});
app.listen(3000, () => console.log('API running on port 3000'));Request Object Cheatsheet
js
req.params.id // URL parameter: /users/:id
req.query.page // Query string: /users?page=2
req.body.name // Request body (JSON)
req.headers['authorization'] // Request headers
req.method // 'GET', 'POST', etc.
req.path // '/users/1'
req.ip // Client IP addressResponse Object Cheatsheet
js
res.json({ data }) // Send JSON (sets Content-Type)
res.send('text') // Send text/HTML
res.status(201).json(data) // Set status + send JSON
res.status(204).send() // No content
res.redirect('/new-url') // Redirect
res.set('X-Custom', 'val') // Set headerREST API Best Practices
- Use nouns for resources:
/users,/products(not/getUsers) - Use HTTP methods for actions, not URL verbs
- Return appropriate status codes (200, 201, 400, 401, 404, 500)
- Version your API:
/api/v1/users - Always return JSON with consistent structure
- Use plural resource names:
/usersnot/user
Consistent Response Format
js
// Success
res.json({ success: true, data: user });
// Error
res.status(400).json({ success: false, error: 'Validation failed' });
// Paginated list
res.json({
success: true,
data: users,
pagination: { page: 1, limit: 10, total: 100 }
});Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.