Building a RESTful API (Representational State Transfer) is the most common use case for Node.js in industry. A well-designed REST API adheres to standard HTTP methods, clean resource-based URLs, strict input validation, and standardized JSON response envelopes.
| HTTP Method | Endpoint URL | Action Description | Expected Status Code |
|---|---|---|---|
GET |
/api/courses |
Retrieve a paginated list of courses | 200 OK |
GET |
/api/courses/:id |
Retrieve details of a single course by ID | 200 OK (or 404) |
POST |
/api/courses |
Create a new course record | 201 Created |
PATCH |
/api/courses/:id |
Update specific fields of an existing course | 200 OK |
DELETE |
/api/courses/:id |
Delete a course record from database | 204 No Content |
const express = require('express');
const app = express();
app.use(express.json());
let courses = [
{ id: 1, title: 'Node.js Master Class', price: 49.99 },
{ id: 2, title: 'React JS Full Stack', price: 59.99 }
];
// 1. GET ALL (with Pagination & Filtering)
app.get('/api/courses', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const maxPrice = parseFloat(req.query.maxPrice);
let filtered = [...courses];
if (!isNaN(maxPrice)) {
filtered = filtered.filter(c => c.price <= maxPrice);
}
const startIndex = (page - 1) * limit;
const paginated = filtered.slice(startIndex, startIndex + limit);
res.status(200).json({
success: true,
page,
totalRecords: filtered.length,
data: paginated
});
});
// 2. CREATE (POST)
app.post('/api/courses', (req, res) => {
const { title, price } = req.body;
if (!title || typeof price !== 'number') {
return res.status(400).json({
success: false,
error: 'Validation Error: title (string) and price (number) are required'
});
}
const newCourse = { id: courses.length + 1, title, price };
courses.push(newCourse);
res.status(201).json({ success: true, data: newCourse });
});
// 3. PARTIAL UPDATE (PATCH)
app.patch('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) return res.status(404).json({ success: false, error: 'Course not found' });
if (req.body.title) course.title = req.body.title;
if (req.body.price) course.price = req.body.price;
res.status(200).json({ success: true, data: course });
});
// 4. DELETE
app.delete('/api/courses/:id', (req, res) => {
const index = courses.findIndex(c => c.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ success: false, error: 'Course not found' });
courses.splice(index, 1);
res.status(204).send(); // 204 No Content
});
app.listen(3000);
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Connect REST endpoints to persistent database collections.
Secure REST API routes with Bearer token authentication.
Automate end-to-end integration tests for REST APIs.