Building REST APIs (Express)

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.

Illustration of Building REST APIs (Express)
Illustration of Building REST APIs (Express)

💡 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.

Express Route Methods for REST
HTTP MethodExpress Handler
GETapp.get(path, callback)
POSTapp.post(path, callback)
PUTapp.put(path, callback)
PATCHapp.patch(path, callback)
DELETEapp.delete(path, callback)

To handle JSON request bodies, use express.json() middleware:

📌 Deep Dive: Using express.json() Middleware

JAVASCRIPT
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

JAVASCRIPT
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, or req.query as 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.