Building a REST API (CRUD)
A REST API uses URLs for things (/products) and HTTP methods for actions. CRUD = Create, Read, Update, Delete:
A REST API is a standard way for apps to talk to a server: URLs name things (/products) and HTTP methods say what to do (GET reads, POST creates, PATCH updates, DELETE removes). Mobile apps, websites and other servers can all use the same API.
GET /products- list,GET /products/:id- one itemPOST /products- create (reply 201)PATCH /products/:id- change some fieldsDELETE /products/:id- remove (reply 204, no body)
Example
import express from "express";
const app = express();
app.use(express.json()); // read JSON request bodies into req.body
let products = [{ id: 1, name: "Kettle", price: 1299 }];
let nextId = 2;
app.get("/products", (req, res) => res.json(products));
app.post("/products", (req, res) => {
const { name, price } = req.body;
if (typeof name !== "string" || !name.trim() || typeof price !== "number" || price <= 0) {
return res.status(400).json({ error: "name (text) and price (a positive number) are required" });
}
const p = { id: nextId++, name: name.trim(), price };
products.push(p);
res.status(201).json(p);
});
app.patch("/products/:id", (req, res) => {
const p = products.find(x => x.id === Number(req.params.id));
if (!p) return res.status(404).json({ error: "Product not found" });
if (typeof req.body.price === "number" && req.body.price > 0) p.price = req.body.price;
res.json(p);
});
app.delete("/products/:id", (req, res) => {
const before = products.length;
products = products.filter(x => x.id !== Number(req.params.id));
if (products.length === before) return res.status(404).json({ error: "Product not found" });
res.status(204).end();
});
app.listen(3000, () => console.log("API ready on port 3000"));
// Start it with: node server.mjs
// API ready on port 3000
// Then try these requests (real replies):
// POST /products {"name":"Iron","price":899}
// -> 201 {"id":2,"name":"Iron","price":899}
// POST /products {"name":"Fan"}
// -> 400 {"error":"name (text) and price (a positive number) are required"}
// PATCH /products/1 {"price":1199}
// -> 200 {"id":1,"name":"Kettle","price":1199}
// DELETE /products/2
// -> 204
// GET /products
// -> 200 [{"id":1,"name":"Kettle","price":1199}]Trying it with curl
Example
curl -X POST http://localhost:3000/products \
-H "Content-Type: application/json" \
-d '{"name": "Iron", "price": 899}'Here the data is in memory, so it's lost when the server restarts. Real apps save it in a database such as PostgreSQL or MongoDB (see the SQL course). Tools like Postman or the VS Code REST Client extension make testing APIs easy.
Key points
- URLs name resources; methods say the action.
- Return the right status codes (201, 204, 400, 404).
- Validate every request body on the server.
📝 Test yourself
1. Which method usually creates a new item?
2. What does app.use(express.json()) do?
3. Fill in the status code for 'created':
res.status().json(p);
