REST API Basics
A REST API exposes resources through predictable URLs and HTTP methods.
A REST API models your data as resources (like users or posts) and uses HTTP methods to act on them. The same URL means different things depending on the verb.
Example
app.use(express.json());
app.get('/api/posts', (req, res) => {
res.json([{ id: 1, title: 'Hello' }]);
});When to use it
- A mobile app backend exposes a REST API so both iOS and Android clients can fetch and update data using standard HTTP verbs.
- A team designs their product API around REST conventions so third-party developers can integrate without reading proprietary docs.
- A developer uses REST principles to version an API at /api/v1 while keeping backward compatibility for existing clients.
More examples
REST resource overview
Implements all five standard REST endpoints for an items resource in under 10 lines using an in-memory array.
const express = require('express');
const app = express();
app.use(express.json());
const items = [];
app.get('/items', (req, res) => res.json(items));
app.get('/items/:id', (req, res) => res.json(items.find(i => i.id == req.params.id)));
app.post('/items', (req, res) => { items.push(req.body); res.status(201).json(req.body); });
app.put('/items/:id', (req, res) => res.json({ updated: true }));
app.delete('/items/:id',(req, res) => res.status(204).send());
app.listen(3000);Consistent JSON error format
Centralises error formatting with a helper so all REST endpoints return the same JSON error shape.
function apiError(res, status, message) {
return res.status(status).json({ error: { status, message } });
}
app.get('/items/:id', (req, res) => {
const item = items.find(i => i.id == req.params.id);
if (!item) return apiError(res, 404, 'Item not found');
res.json(item);
});API versioning with a router
Mounts two router instances under versioned prefixes so the v2 response shape can differ without breaking v1 clients.
const v1 = require('express').Router();
v1.get('/items', (req, res) => res.json({ version: 1, items: [] }));
const v2 = require('express').Router();
v2.get('/items', (req, res) => res.json({ version: 2, data: [], meta: {} }));
app.use('/api/v1', v1);
app.use('/api/v2', v2);
Discussion