A REST API is a promise to other programmers, including the front-end developer who joins next year. If the URLs and replies are predictable, they can use your API without asking you questions. If they are not, every endpoint becomes a small mystery. This lesson collects the habits that make an API predictable, and shows each one in a tested example of 45 products.
Nouns for URLs, verbs for methods
A URL names a thing, and the HTTP method says what to do with it. Use plural nouns: /api/v1/products is the collection and /api/v1/products/7 is one item. GET reads, POST creates, PUT replaces, PATCH changes part of it, and DELETE removes it. Avoid verbs in paths such as /getProducts or /deleteProduct, because the method already says that. For relations, nest only one level: /users/5/orders is clear, while /users/5/orders/9/items/3/notes is a sign to flatten.
Status codes that tell the truth
- 200 OK for a successful read or update. 201 Created after a
POST, with aLocationheader holding the new URL. 204 No Content for a delete. - 400 when the request is malformed. 401 when the user is not logged in. 403 when the user is logged in but not allowed. 404 when the item does not exist.
- 409 Conflict when the request clashes with the current state, for example a duplicate email. 422 when the data is well-formed but fails the rules, for example a negative price.
- 429 when the client sent too many requests. 500 for your own bugs. Never send 200 with an error message inside; clients and monitoring tools trust the code.
The most common mistakes are using 200 for everything and mixing up 401 and 403. 401 really means *unauthenticated*: we do not know who you are. 403 means we know you, and the answer is still no.
Paging, filtering, sorting and search
A list endpoint that returns every row works on your laptop and fails in production. The fix is paging: the client asks for a page and a size. The server must also set a maximum size, otherwise a client can ask for limit=1000000. In the code, clamp keeps numbers inside a safe range and falls back to a default when the value is not a number at all. Filtering, sorting and search then narrow the list. Sorting only accepts a short list of allowed field names, never a field name copied straight from the URL, because a free field name can expose private fields or break database queries.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install express. - Save the code as
api.js. The test below it needsnpm install -D supertestand runs withnode --test.
import express from 'express';
const categories = ['books', 'games', 'tools'];
export const products = Array.from({ length: 45 }, (_, i) => ({
id: i + 1,
name: `Item ${String(i + 1).padStart(2, '0')}`,
price: 100 + ((i * 37) % 400),
category: categories[i % 3],
}));
const clamp = (value, min, max, fallback) => {
const number = Number.parseInt(value, 10);
return Number.isNaN(number) ? fallback : Math.min(Math.max(number, min), max);
};
export function createApp() {
const app = express();
app.use(express.json());
// Version 1: list with paging, filtering, sorting and search.
app.get('/api/v1/products', (req, res) => {
const page = clamp(req.query.page, 1, 1_000_000, 1);
const limit = clamp(req.query.limit, 1, 50, 10); // never let a client ask for everything
const { category, minPrice, maxPrice, q } = req.query;
const sortField = ['price', 'name', 'id'].includes(req.query.sort) ? req.query.sort : 'id';
const direction = req.query.order === 'desc' ? -1 : 1;
let items = products;
if (category) items = items.filter((p) => p.category === category);
if (minPrice) items = items.filter((p) => p.price >= Number(minPrice));
if (maxPrice) items = items.filter((p) => p.price <= Number(maxPrice));
if (q) items = items.filter((p) => p.name.toLowerCase().includes(String(q).toLowerCase()));
items = [...items].sort((a, b) => (a[sortField] > b[sortField] ? 1 : a[sortField] < b[sortField] ? -1 : 0) * direction);
const total = items.length;
const data = items.slice((page - 1) * limit, page * limit);
res.json({ data, meta: { page, limit, total, totalPages: Math.ceil(total / limit) } });
});
// Version 2 changes the shape of the answer, so it lives at a new address.
app.get('/api/v2/products', (req, res) => {
res.set('Deprecation', 'false');
res.json({ items: products.slice(0, 5).map((p) => ({ id: p.id, title: p.name, priceInr: p.price })) });
});
// Create returns 201 and a Location header. Duplicates return 409.
app.post('/api/v1/products', (req, res) => {
const { name, price, category } = req.body ?? {};
if (typeof name !== 'string' || !name.trim() || typeof price !== 'number' || price < 0) {
return res.status(422).json({ error: 'name and a non-negative price are required' });
}
if (products.some((p) => p.name.toLowerCase() === name.trim().toLowerCase())) {
return res.status(409).json({ error: 'A product with this name already exists' });
}
const product = { id: products.length + 1, name: name.trim(), price, category: category ?? 'tools' };
products.push(product);
res.status(201).location(`/api/v1/products/${product.id}`).json(product);
});
app.use((req, res) => res.status(404).json({ error: 'Not found' }));
return app;
}
Try these URLs once the app is listening: /api/v1/products?page=2&limit=5, /api/v1/products?category=books&sort=price&order=desc, and /api/v1/products?q=item 0. Return a small envelope with the data and the paging details, such as the current page, the size and the total count, so a front end can draw page buttons. For very large or fast-changing data, cursor paging ("give me the items after this id") is more stable than page numbers, but page numbers are simpler and enough for most projects.
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './r20-api.js';
const app = createApp();
test('paging', async () => {
const res = await request(app).get('/api/v1/products?page=2&limit=10');
assert.equal(res.body.data.length, 10);
assert.equal(res.body.data[0].id, 11);
assert.deepEqual(res.body.meta, { page: 2, limit: 10, total: 45, totalPages: 5 });
});
test('limit is capped and bad numbers fall back', async () => {
const res = await request(app).get('/api/v1/products?limit=9999&page=abc');
assert.equal(res.body.meta.limit, 50);
assert.equal(res.body.meta.page, 1);
});
test('filter, sort and search', async () => {
const cheap = await request(app).get('/api/v1/products?category=books&maxPrice=200&sort=price&order=desc');
assert.ok(cheap.body.data.length > 0);
assert.ok(cheap.body.data.every((p) => p.category === 'books' && p.price <= 200));
const prices = cheap.body.data.map((p) => p.price);
assert.deepEqual(prices, [...prices].sort((a, b) => b - a));
const found = await request(app).get('/api/v1/products?q=item 07');
assert.deepEqual(found.body.data.map((p) => p.id), [7]);
});
test('status codes', async () => {
const created = await request(app).post('/api/v1/products').send({ name: 'Lamp', price: 250 });
assert.equal(created.status, 201);
assert.equal(created.headers.location, `/api/v1/products/${created.body.id}`);
assert.equal((await request(app).post('/api/v1/products').send({ name: 'lamp', price: 1 })).status, 409);
assert.equal((await request(app).post('/api/v1/products').send({ name: '', price: 1 })).status, 422);
});
test('version 2 has its own shape', async () => {
const res = await request(app).get('/api/v2/products');
assert.equal(res.body.items[0].priceInr > 0, true);
});
ok 1 - paging
ok 2 - limit is capped and bad numbers fall back
ok 3 - filter, sort and search
ok 4 - status codes
ok 5 - version 2 has its own shape
Versioning
Once other people use your API you cannot freely change replies, or their apps break. A version in the URL, /api/v1 and /api/v2, lets you publish a new shape while the old one keeps working. The example has a version 2 that changes the shape of the list reply. Do not create a new version for every small change. Adding a new field is safe in the same version. Renaming or removing a field is the kind of change that needs v2. Announce the end date of an old version in advance, and keep it running until then.
Your task
- Add
DELETE /api/v1/products/:idthat returns 204, and 404 for a missing id. - Add a
fieldsquery, for example?fields=name,price, that returns only the allowed fields. - Return the total number of pages in the reply and write a test for the last page.
How to check it worked
- Your five tests pass.
limit=9999returns at most 50 items.- A bad
sortvalue falls back toidinstead of crashing.