Full CRUD REST API Example
14 min read
Full CRUD REST API Example
A REST API exposes resources over HTTP using the four CRUD operations: Create (POST), Read (GET), Update (PUT/PATCH), and Delete (DELETE). Here is a self-contained in-memory example for a /users resource.
js
import express from "express";
const app = express();
app.use(express.json());
let users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
let nextId = 3;
// READ ALL
app.get("/users", (req, res) => {
res.json(users);
});
// READ ONE
app.get("/users/:id", (req, res) => {
const user = users.find(u => u.id === Number(req.params.id));
if (!user) return res.status(404).json({ error: "Not found" });
res.json(user);
});
// CREATE
app.post("/users", (req, res) => {
const user = { id: nextId++, name: req.body.name };
users.push(user);
res.status(201).json(user);
});
// UPDATE
app.put("/users/:id", (req, res) => {
const idx = users.findIndex(u => u.id === Number(req.params.id));
if (idx === -1) return res.status(404).json({ error: "Not found" });
users[idx] = { id: Number(req.params.id), name: req.body.name };
res.json(users[idx]);
});
// DELETE
app.delete("/users/:id", (req, res) => {
users = users.filter(u => u.id !== Number(req.params.id));
res.status(204).send();
});
app.listen(3000);This example is intentionally simple. In a real application you would replace the in-memory array with database calls and add input validation, authentication, and proper error handling.
CPCODELAB students build a version of this pattern in every backend module — it is the skeleton that every more advanced pattern (auth, caching, pagination) is attached to.
Ready to test yourself?
Practice Express— quiz & coding exercises