Skip to main content
Practice Problems

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 MethodCRUDDescription
GETReadRetrieve a resource
POSTCreateCreate a new resource
PUTUpdate (full)Replace a resource
PATCHUpdate (partial)Modify a resource
DELETEDeleteRemove 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 address

Response 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 header

REST API Best Practices

  1. Use nouns for resources: /users, /products (not /getUsers)
  2. Use HTTP methods for actions, not URL verbs
  3. Return appropriate status codes (200, 201, 400, 401, 404, 500)
  4. Version your API: /api/v1/users
  5. Always return JSON with consistent structure
  6. Use plural resource names: /users not /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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems