Building a Simple REST API
Time to combine everything from this course into one working example: an in-memory REST API for managing a list of users, with routes to list and create them.
The full server
JS server.js
const express = require("express");
const app = express();
app.use(express.json());
let users = [
{ id: 1, name: "Priya" },
{ id: 2, name: "Sam" },
];
app.get("/users", (req, res) => {
res.json(users);
});
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: "User not found" });
}
res.json(user);
});
app.post("/users", (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
};
users.push(newUser);
res.status(201).json(newUser);
});
app.listen(3000, () => {
console.log("API running at http://localhost:3000/");
});
Trying it out
bash terminal
curl http://localhost:3000/users
Output
[{"id":1,"name":"Priya"},{"id":2,"name":"Sam"}]bash terminal
curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name":"Jordan"}'
Output
{"id":3,"name":"Jordan"}bash terminal
curl http://localhost:3000/users/99
Output
{"error":"User not found"}Walking through it: GET /users returns the whole array as JSON via res.json(). GET /users/:id looks one up by id, returning a 404 with an error body if nothing matches. POST /users reads the new name from req.body — parsed automatically by the express.json() middleware — assigns it an id, and returns 201 Created along with the new record.
Note: this API's "database" is just an in-memory array — it resets to the two starting users every time the server restarts, and won't survive a crash or a second server instance. A real API would persist to an actual database instead, but the routing, status codes, and request/response shape here are exactly the pattern you'd use with one.
Course complete: that covers the Node.js course from top to bottom — modules and
require/module.exports, the file system module, building a server with raw http, npm and package.json, the move from callbacks to promises to async/await, EventEmitter, environment variables, and Express — ending with a small but complete REST API. From here, the natural next steps are connecting to a real database and deploying a Node app to a live server.