How Do You Build a REST API with Express.js?
Step-by-step guide to building a REST API with Express.js — routes, middleware, JSON parsing, status codes, and error handling with real code examples.
Expected Interview Answer
You build a REST API with Express.js by creating an app instance, defining routes that map HTTP methods (GET, POST, PUT, DELETE) to resource endpoints, adding middleware for parsing and cross-cutting concerns, and starting a server with app.listen.
Express is a minimal, unopinionated web framework where you compose functionality through middleware and routers. You use express.json() to parse request bodies, group related endpoints with express.Router(), send JSON responses with res.json() and appropriate status codes, and centralize error handling in a four-argument error middleware. RESTful design means using nouns for resources, HTTP verbs for actions, and correct status codes (200, 201, 404, 500).
- Minimal, flexible and widely adopted
- Middleware pipeline for reusable logic
- Routers keep code organized by resource
- Simple JSON handling and status codes
- Large ecosystem of compatible packages
AI Mentor Explanation
Building an Express API is like organizing a cricket match with clear roles and rules. Routes are the field positions each mapping a specific delivery to a specific fielder, middleware are the umpires who inspect every ball before it counts, and status codes are the signals — four, six, or out. app.listen is the toss that starts play, letting requests come in over after over to the right handler.
Step-by-Step Explanation
Step 1
Create the app
Import express and create an instance with const app = express() to hold routes and middleware.
Step 2
Add parsing middleware
Use app.use(express.json()) so JSON request bodies are parsed into req.body.
Step 3
Define RESTful routes
Map HTTP methods to resource paths: GET /users, POST /users, GET /users/:id, PUT and DELETE.
Step 4
Send proper responses
Reply with res.status(code).json(data), using 200, 201, 404, and 500 appropriately.
Step 5
Add error handling
Define a four-argument middleware (err, req, res, next) at the end to catch and format errors.
Step 6
Start the server
Call app.listen(port, callback) to begin accepting requests.
What Interviewer Expects
- Mapping HTTP methods to CRUD operations
- Understanding middleware and its ordering
- Using express.Router to organize endpoints
- Sending correct status codes and JSON
- Centralized error-handling middleware
Common Mistakes
- Forgetting express.json() and getting undefined req.body
- Using wrong or default status codes
- Placing error middleware before routes
- Not handling async errors and unhandled rejections
- Designing verbs into URLs instead of using HTTP methods
Best Answer (HR Friendly)
“You build a REST API in Express by defining routes that respond to web requests like GET and POST for each type of data, adding small helper functions called middleware to handle things like reading the request body, and then starting a server to listen for traffic. Each route returns data and a status code telling the client whether it worked.”
Code Example
const express = require('express');
const app = express();
app.use(express.json()); // parse JSON bodies into req.body
const users = [{ id: 1, name: 'Ada' }];
// Read all
app.get('/users', (req, res) => {
res.status(200).json(users);
});
// Read one
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: 'Not found' });
res.json(user);
});
// Create
app.post('/users', (req, res) => {
const user = { id: users.length + 1, name: req.body.name };
users.push(user);
res.status(201).json(user);
});
// Central error handler (four args)
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal Server Error' });
});
app.listen(3000, () => console.log('API on port 3000'));Follow-up Questions
- What is middleware in Express and how does ordering matter?
- How does express.Router help structure a larger API?
- Which status codes map to create, read, update, and delete?
- How do you handle async errors in Express route handlers?
- How would you add validation and authentication middleware?
MCQ Practice
1. Which middleware parses JSON request bodies in modern Express?
express.json() is built into Express and populates req.body from JSON request payloads.
2. What status code best represents a successful resource creation?
201 Created signals that a new resource was successfully created, typically returning the new resource.
3. How is Express error-handling middleware identified?
Express treats a middleware function with four parameters as an error handler and passes errors to it.
Flash Cards
How do you parse JSON bodies in Express? — app.use(express.json()) populates req.body.
Which method starts an Express server? — app.listen(port, callback).
How is error-handling middleware defined? — A function with four arguments: (err, req, res, next).
What status code means a resource was created? — 201 Created.
How do you organize routes by resource? — Use express.Router() and mount it with app.use().