Build a REST API
A REST API is a set of rules for how a server shares data with clients. When an app loads a list of products or saves a new comment, it talks to an API. The server answers with JSON, and the app renders it. REST is the style most web APIs follow, and Express is the usual way to build one in Node.js.
REST works with four main actions that map to the HTTP methods you already met. GET fetches data, POST creates new data, PUT or PATCH updates it, and DELETE removes it. The URL says which resource you mean, like /api/products or /api/products/3, and the method says what to do with it. The same URL can answer four different questions depending on the method.
Every response should carry a status code. 200 means success, 201 means created, 404 means not found, and 500 means the server failed. Clients read the code before they read the body, so returning the right one is part of building a correct API. With a few routes and status codes, you have a real backend that any frontend can use.
Your first API route
An Express route pairs a method and a path with a handler. app.get("/api/products") runs when a GET request arrives at that path. The handler sends a JSON response with res.json. Express sets the Content-Type and converts the object for you.
app.get("/api/products", (req, res) => {
res.json(products); // sends JSON, not a web page
});
POST creates data
A POST route receives data in req.body. Express needs express.json() middleware to parse JSON bodies. Validate what arrives, create the item, and answer with 201 plus the new object. Clients use this route when a user submits a form.
app.use(express.json());
app.post("/api/products", (req, res) => {
const product = { id: products.length + 1, name: req.body.name };
products.push(product);
res.status(201).json(product);
});
Route parameters
A colon in the path marks a parameter. app.get("/api/products/:id") captures the id from the URL as req.params.id. Use it to look up one item, and answer 404 with an error object when nothing matches.
app.get("/api/products/:id", (req, res) => {
const found = products.find((p) => p.id === Number(req.params.id));
if (!found) {
return res.status(404).json({ error: "Product not found" });
}
res.json(found);
});
Syntax
const express = require("express");
const app = express();
app.use(express.json());
const products = [
{ id: 1, name: "Shirt", price: 1200 },
{ id: 2, name: "Hat", price: 900 }
];
app.get("/api/products", (req, res) => {
res.json(products);
});
app.post("/api/products", (req, res) => {
const product = { id: products.length + 1, name: req.body.name };
products.push(product);
res.status(201).json(product);
});
app.listen(3000, () => {
console.log("API running on port 3000");
});
Express res.json Sets Content-Type Automatically
res.json(obj) sets JSON header and stringifies — don't JSON.stringify manually.
app.get("/api", (req,res)=>res.json({ok:true}))
Good to know
- GET reads, POST creates, PUT or PATCH updates, DELETE removes.
- Express routes pair a method and a path with a handler.
- express.json() middleware is required to read JSON bodies.
- Use status codes: 200 success, 201 created, 404 not found, 500 server error.
- Route parameters like :id capture values from the URL.