Express is a minimalist web framework for Node.js used to build RESTful APIs efficiently. REST APIs allow communication between client and server using standard HTTP methods.

💡 Core HTTP Methods in REST APIs
- GET – Retrieve data
- POST – Create new data
- PUT – Update existing data (replace)
- PATCH – Update existing data (partial)
- DELETE – Remove data
With Express, you define routes that correspond to these HTTP methods and implement logic to handle requests and send responses.
| HTTP Method | Express Handler |
|---|---|
| GET | app.get(path, callback) |
| POST | app.post(path, callback) |
| PUT | app.put(path, callback) |
| PATCH | app.patch(path, callback) |
| DELETE | app.delete(path, callback) |
To handle JSON request bodies, use express.json() middleware:
📌 Deep Dive: Using express.json() Middleware
const express = require('express');
const app = express();
app.use(express.json()); // Parse incoming JSON payloads
Here is a minimal example showing how to implement CRUD operations for a simple resource, such as /items:
📌 Deep Dive: CRUD Routes Example
let items = [];
app.get('/items', (req, res) => {
res.json(items);
});
app.post('/items', (req, res) => {
const newItem = req.body;
items.push(newItem);
res.status(201).json(newItem);
});
app.put('/items/:id', (req, res) => {
const id = req.params.id;
const updatedItem = req.body;
items = items.map(item => (item.id === id ? updatedItem : item));
res.json(updatedItem);
});
app.delete('/items/:id', (req, res) => {
const id = req.params.id;
items = items.filter(item => item.id !== id);
res.status(204).end();
});
💡 Route Parameters
Use colon-prefixed segments in paths (e.g., /items/:id) to capture dynamic values accessible via req.params.
⚠️ Important: Status Codes
Always respond with appropriate HTTP status codes: 200 (OK), 201 (Created), 204 (No Content), 400 (Bad Request), 404 (Not Found), etc., so clients understand the result.
Summary of typical REST API flow:
- Client sends HTTP request (GET, POST, PUT, PATCH, DELETE) to an endpoint.
- Express route handler processes request, accesses
req.params,req.body, orreq.queryas needed. - Handler performs data operations (e.g., read, store, update, delete).
- Handler sends JSON response with proper status code.
💡 Using Middleware for Error Handling
Define error-handling middleware with four arguments (err, req, res, next) to catch and respond to errors consistently.
Express makes building REST APIs straightforward with its simple routing and middleware system. Start small, test endpoints, and incrementally add features.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which Express method handles HTTP POST requests for creating resources?
Question 2 of 2
In Express, how do you access a dynamic route parameter named id in /items/:id?
Loading results...