Express REST API quickstart: hello world to JSON endpoints
Express is the minimal Node.js web framework: a few lines give you a working HTTP server, and its routing maps cleanly onto REST endpoints. This quickstart takes you from hello world to a small JSON API, from the official Express starter docs.
Hello world
After npm install express, one file is a full app:
import express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
app.get registers a handler for GET requests to a path; res.send writes the response; app.listen starts the server.
Routing = REST endpoints
Express's basic routing doc maps HTTP methods to handler registrations. That is your REST API vocabulary:
app.use(express.json()); // parse JSON request bodies
let orders = [];
app.get('/api/orders', (req, res) => {
res.json(orders);
});
app.post('/api/orders', (req, res) => {
const order = { id: orders.length + 1, ...req.body };
orders.push(order);
res.status(201).json(order);
});
GET reads, POST creates. res.json sends a JSON response, and res.status(201) sets the status before it.
Route parameters
app.get('/api/orders/:id', (req, res) => {
const order = orders.find(o => o.id === Number(req.params.id));
if (!order) return res.status(404).json({ error: 'not found' });
res.json(order);
});
:id captures part of the path into req.params; always return a proper 404 when the thing is missing instead of an empty 200.
Common mistakes
- Forgetting
express.json()and then wondering whyreq.bodyis undefined. - Sending a response twice (calling
res.sendthen falling through to anotherres.json); return early after the first send. - Serving everything from the root path; mount related routes under a prefix like
/api.
Next: call your API from the browser with fetch, and keep ports and hosts sane across environments when you deploy.
