ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Node.js Tutorial• 8 min read

Building Web Servers & REST APIs with Express.js

Routing, request handling, status codes, and JSON response delivery

Express is the de facto minimalist web framework for Node.js, providing robust routing, middleware hooks, and HTTP helper utilities that make building production APIs fast and intuitive.

Express Routing and Request Parameters

HTTP methods: app.get(), app.post(), app.put(), app.patch(), app.delete().

Route parameters: Extract dynamic path segments via req.params (e.g., /api/courses/:id).

Query parameters: Access query strings via req.query (e.g., ?sort=desc&limit=10).

Automatic JSON parsing: express.json() middleware parses incoming JSON bodies into req.body.

REST API with Express (app.js)
import express from 'express';

const app = express();
app.use(express.json()); // Body-parser for JSON payloads

const courses = [
  { id: 1, title: 'Node.js Microservices', students: 1200 },
  { id: 2, title: 'TypeScript Deep Dive', students: 950 }
];

// GET all courses
app.get('/api/courses', (req, res) => {
  res.status(200).json({ success: true, data: courses });
});

// GET single course with route parameter
app.get('/api/courses/:id', (req, res) => {
  const id = parseInt(req.params.id, 10);
  const course = courses.find(c => c.id === id);
  
  if (!course) {
    return res.status(404).json({ success: false, message: 'Course not found' });
  }
  res.json({ success: true, data: course });
});

// POST create course
app.post('/api/courses', (req, res) => {
  const { title } = req.body;
  if (!title) {
    return res.status(400).json({ error: 'Course title is required' });
  }
  const newCourse = { id: courses.length + 1, title, students: 0 };
  courses.push(newCourse);
  res.status(201).json({ success: true, data: newCourse });
});

app.listen(4000, () => console.log('API live on port 4000'));
Express provides clean, expressive HTTP status code and response methods.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which middleware is required in Express to automatically parse incoming JSON request bodies?