Explain it simply
Reading users in plain language
Reading is the safest thing a client does: GET asks, the server answers, and nothing on the server changes. Two reads cover most of a users API. GET /v1/users/u_2 asks for one specific user ("show me this file"), and GET /v1/users?role=member&limit=2 asks for a list ("show me the members, two at a time"). Because GET changes nothing, it can be repeated, cached and retried freely. That freedom is also the catch: every successful read is data leaving the building, so the server must be careful about what it reveals.
Problem → Why → Solution
The problem: sending the database row back as it is
The quickest way to build GET /v1/users/:id is to look the row up and send it back. If the table has a passwordHash column, it goes out in the JSON. If the endpoint only checks that the caller is logged in, any logged-in user can read any other user's record by changing the id in the URL (broken object level authorization, the first item on the OWASP API Security list). And a list endpoint that returns every row turns one request into a megabyte response as the table grows.
app.get("/v1/users/:id", requireLogin, async (req, res) => {
const user = await db.users.findById(req.params.id);
res.json(user); // includes passwordHash, and works for ANY id
});A read asks two questions
The two questions are: does the resource exist, and may this caller see it? Answering only the first leaks data, and sending the raw database row leaks columns nobody meant to publish. Decide the public shape explicitly, and decide for each request who may see what.
Core concept: one resource, one collection and a cache validator
There are two read shapes. GET /v1/users/{id} returns one resource: 200 with the user and an ETag header, or 404 with the standard error body when no such user exists. GET /v1/users returns a collection wrapped in an envelope, { items: [...], next_cursor }, never a bare array, so that fields like next_cursor can be added later without breaking clients. The collection accepts a filter (?role=member), a page size (?limit=2) and the cursor from the pagination lesson. Query validation follows the same rules as bodies: an invalid limit is a 422 with a message for that field.
Serialization is an allowlist. The stored record may hold a passwordHash, internal notes and a version counter, but the response is built by picking the public fields (id, name, email, role, bio), not by deleting the secret ones. With picking, a column added next month stays private until someone decides to publish it; with deleting, it leaks by default. Also decide what even legitimate callers may see: an email address may be visible to admins and to the user themself but not to other members.
Authorization comes before the existence of the resource is revealed. For GET /v1/users/u_2 the server checks that the caller may read u_2. If not, a 404 is often better than a 403, because a 403 confirms that the id exists. Check the permission for every id inside the handler, not once at login.
| Request | Response | Meaning |
|---|---|---|
| GET /v1/users/u_2 | 200 + ETag | here is the user |
| GET with a current If-None-Match | 304, no body | your copy is current |
| GET /v1/users/u_99 | 404 user_not_found | no such user |
| GET /v1/users?limit=0 | 422 validation_failed | bad query parameter |
Every response to GET /v1/users/u_2 carries an ETag, a validator that changes whenever the resource changes (here "v1", "v2" and so on). The next time the client asks, it sends If-None-Match: "v1". If the resource is still at v1, the server answers 304 Not Modified with no body and the client reuses its copy: no data transferred, nothing serialized. A 304 gives res.ok false, because ok covers statuses 200 to 299, so check the status. A 304 is not an error; it is this mechanism succeeding. A browser's HTTP cache can do this for you; when you send the header yourself, as the sample does, you see the 304 yourself.
- Find the record (404 if missing)
- Check this caller may see it
- Pick the public fields only
- Add ETag; 304 if client is current
A read answers "what may this caller see?", not "what is in the database?".
General pattern
GET /v1/<collection>/<id>
200 OK ETag: "<version>" { <public fields only> }
404 Not Found { "error": { "code": "...", "message": "..." } }
GET /v1/<collection>?<filter>=<value>&limit=<n>&cursor=<opaque>
200 OK { "items": [ ... ], "next_cursor": "<opaque>" | null }
GET /v1/<collection>/<id> If-None-Match: "<version>"
304 Not Modified (no body)A single resource answers 200 (with an ETag) or 404, a collection answers with an envelope driven by filter, limit and cursor, and a client that already holds the current version gets a 304.
Worked example: a GET, a conditional GET and a list
This sample runs the users API on a random local port. The database rows carry a passwordHash; watch it never appear in a response. The client reads u_2 and remembers the ETag, then asks again with that ETag and gets a bodyless 304. After that it tries a missing id (404), reads the members one at a time with a cursor, and sends a bad limit and a bad cursor (422 and 400).
import http from "node:http";
// The users API (stands in for https://api.example.com/v1/users).
// "stored" holds database rows, which have private columns clients must not see.
const row = (n, name, role, bio = null) => ({
id: "u_" + n,
name,
email: name.toLowerCase() + "@example.com",
role,
bio,
version: 1,
passwordHash: "$2b$10$not-a-real-hash",
});
const stored = [
row(1, "Alice", "admin", "Maintainer"),
row(2, "Bob", "member"),
row(3, "Carol", "member"),
];
// The public shape is a pick: a column added later stays private by default
const publicView = ({ id, name, email, role, bio }) => ({ id, name, email, role, bio });
const etagOf = (user) => '"v' + user.version + '"';
const num = (user) => Number(user.id.slice(2)); // "u_3" -> 3
const encode = (n) => Buffer.from(JSON.stringify({ after: n })).toString("base64url");
function decode(cursor) {
try {
const { after } = JSON.parse(Buffer.from(cursor, "base64url").toString());
return Number.isInteger(after) ? after : null;
} catch {
return null;
}
}
const send = (res, status, body, headers = {}) => {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(body === undefined ? undefined : JSON.stringify(body));
};
const fail = (res, status, code, message, fields) =>
send(res, status, { error: { code, message, ...(fields && { fields }) } });
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost");
const [, , resource, id] = url.pathname.split("/");
if (req.method !== "GET" || resource !== "users") {
return fail(res, 404, "not_found", "No such route");
}
if (id) {
const user = stored.find((u) => u.id === id);
if (!user) return fail(res, 404, "user_not_found", "No user with id " + id);
// Conditional GET: the client already holds this exact version
if (req.headers["if-none-match"] === etagOf(user)) {
return send(res, 304, undefined, { ETag: etagOf(user) });
}
return send(res, 200, publicView(user), { ETag: etagOf(user) });
}
// List: ?role= filter, ?limit= page size, ?cursor= bookmark
const params = url.searchParams;
const limit = Number(params.get("limit") ?? 2);
if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
const fields = { limit: "must be an integer from 1 to 100" };
return fail(res, 422, "validation_failed", "Invalid query", fields);
}
const after = params.has("cursor") ? decode(params.get("cursor")) : 0;
if (after === null) return fail(res, 400, "invalid_cursor", "Unknown cursor");
const role = params.get("role");
const matches = stored.filter((u) => (!role || u.role === role) && num(u) > after);
const items = matches.slice(0, limit).map(publicView);
const next = matches.length > limit ? encode(num(matches[limit - 1])) : null;
send(res, 200, { items, next_cursor: next });
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + server.address().port;
// The client
async function read(path, headers = {}) {
const res = await fetch(base + path, { headers });
const text = await res.text(); // empty for a 304
const body = text ? JSON.parse(text) : null;
return { status: res.status, ok: res.ok, etag: res.headers.get("etag"), body };
}
const bob = await read("/v1/users/u_2");
console.log(bob.status, bob.etag, JSON.stringify(bob.body));
const same = await read("/v1/users/u_2", { "If-None-Match": bob.etag });
console.log("conditional GET:", same.status, "ok:", same.ok, "body:", same.body);
const missing = await read("/v1/users/u_99");
console.log(missing.status, JSON.stringify(missing.body.error));
let cursor = null;
do {
const query = "?role=member&limit=1" + (cursor ? "&cursor=" + cursor : "");
const page = await read("/v1/users" + query);
const names = page.body.items.map((u) => u.name).join(", ");
console.log("members:", names, "| more:", page.body.next_cursor !== null);
cursor = page.body.next_cursor;
} while (cursor);
const badLimit = await read("/v1/users?limit=0");
console.log(badLimit.status, JSON.stringify(badLimit.body.error.fields));
const badCursor = await read("/v1/users?cursor=garbage");
console.log(badCursor.status, badCursor.body.error.code);
server.close();Code breakdown
- The public shape is a pick
const publicView = ({ id, name, email, role, bio }) => ({ id, name, email, role, bio });Destructuring and rebuilding just five fields means passwordHash and version can never reach a response. A new column added to the row stays out until someone adds it here.
- ETag from the version
const etagOf = (user) => '"v' + user.version + '"';The validator "v1" is derived from a version counter. The quotes are part of the ETag format and are sent with it. Every update bumps the version, so the ETag changes.
- Conditional GET
if (req.headers["if-none-match"] === etagOf(user)) {If the If-None-Match the client sent equals the current ETag, the server answers 304 with no body. Node lowercases header names, which is why the index is lowercase.
- 404 with the shared error body
if (!user) return fail(res, 404, "user_not_found", "No user with id " + id);The error for a missing user has the same code and message shape you saw in the create lesson, so one client error handler covers it.
- Filter and cursor in one pass
const matches = stored.filter((u) => (!role || u.role === role) && num(u) > after);The role filter and the cursor's "after" are applied in one filter. With two members and limit=1, Bob comes first and Carol after him.
- A 304 has no body
const text = await res.text(); // empty for a 304A 304 has no body, so calling res.json() directly throws SyntaxError: Unexpected end of JSON input. The helper reads the text first and parses only when it is not empty.
200 "v1" {"id":"u_2","name":"Bob","email":"bob@example.com","role":"member","bio":null}
conditional GET: 304 ok: false body: null
404 {"code":"user_not_found","message":"No user with id u_99"}
members: Bob | more: true
members: Carol | more: false
422 {"limit":"must be an integer from 1 to 100"}
400 invalid_cursor- Look the record up by id
- Check this caller may see it
- Compare the ETag with If-None-Match
- Pick the public fields and respond
Missing or not allowed
404 user_not_found, the same answer in both cases
Found and allowed
200 with ETag, or 304 when the client is current
Who may read what: the ownership check
This is how the BOLA from the problem section is closed. An admin may read everyone and a member may read only themself. Notice that a missing id and someone else's id get the same response (404), so an outsider cannot probe which ids exist. Real tokens and login were covered in the authentication lessons, so here the viewer is simply a function parameter.
const users = [
{ id: "u_1", role: "admin" },
{ id: "u_2", role: "member" },
{ id: "u_3", role: "member" },
];
// Admins can read everyone; members can read only themselves
const canRead = (viewer, target) => viewer.role === "admin" || viewer.id === target.id;
function getUser(viewer, id) {
const target = users.find((u) => u.id === id);
if (!target || !canRead(viewer, target)) {
return { status: 404, body: { error: { code: "user_not_found" } } };
}
return { status: 200, body: target };
}
const [admin, bob] = users;
console.log(getUser(bob, "u_2").status); // 200: his own record
console.log(getUser(bob, "u_3").status); // 404: someone else's record
console.log(getUser(bob, "u_99").status); // 404: no such user, the same answer
console.log(getUser(admin, "u_3").status); // 200: admins may read everyoneA conditional GET on the wire
Here is the raw form with all the headers. A 304 response has no body, and needs no Content-Length. On responses that carry personal data, add Cache-Control: private (or no-store for very sensitive data) so shared caches such as a CDN do not keep personal data.
GET /v1/users/u_2 HTTP/1.1
Host: api.example.com
If-None-Match: "v1"
HTTP/1.1 304 Not Modified
ETag: "v1"curl -i https://api.example.com/v1/users/u_2 -H 'If-None-Match: "v1"'In real projects
Read endpoints in real projects
Read endpoints carry most of an API's traffic, so handling them well matters for both performance and security. A profile page usually calls something like GET /v1/users/me, and an admin dashboard reads a list with a filter and a cursor. Some APIs, GitHub among them, advertise ETag and conditional requests as a way to save rate-limit budget; check the provider's docs for the exact rules.
- Tests try your own record, someone else's, a missing id and an admin, and confirm passwordHash is absent from every response.
- Every list endpoint has a default and a maximum limit; one without them rarely survives long in production.
- Mobile apps use ETags so an unchanged profile is not downloaded again, which reduces data usage.
Common mistakes
Common mistakes when reading
Returning the raw database row
res.json(user) publishes every column, so passwordHash and internal flags leak. Write a list of fields to publish, not a list of fields to remove.
Checking only that the caller is logged in
If being authenticated is enough to read any id, every user can read other people's records by changing the id. Check inside the handler that this caller may read this id.
Treating a 304 as an error, or calling json() on it
A 304 has res.ok false, but it is a success. It also has no body, so res.json() throws SyntaxError: Unexpected end of JSON input. Check for status 304 separately and use your cached copy.
Returning a list with no limit
A GET /v1/users that works with ten rows runs out of memory and times out at a million. Add a limit, a maximum and a cursor from the start.
Best practices
Best practices
- Return collections in an envelope ({ items, next_cursor }), never as a bare array.
- Test the serializer: put a passwordHash in the row and assert it is absent from the response.
- Derive the ETag from a version counter; it is faster and simpler than hashing the response body.
Mini challenge
Write readUser yourself
Write readUser(viewer, id, ifNoneMatch), returning { status, etag, body }. Answer 404 for an id that does not exist or that the viewer may not see (the same answer for both), add an ETag of "v<version>" when allowed, return a bodyless 304 when If-None-Match matches, and otherwise 200 with the public view, without passwordHash. A member may read only themself and an admin may read everyone.
- Use 404 { error: { code: "user_not_found" } } for both missing and not-allowed
- The ETag has the form "v" + version, quotes included
- 304 with no body when If-None-Match equals the ETag
- The 200 body has only id, name, email and role (no passwordHash)
const user = (n, name, role, version = 1) => ({
id: "u_" + n,
name,
email: name.toLowerCase() + "@example.com",
role,
version,
passwordHash: "not-a-real-hash",
});
const users = [user(1, "Alice", "admin"), user(2, "Bob", "member")];
function publicView(user) {
// TODO: return only id, name, email and role
}
function canRead(viewer, target) {
// TODO: admins read everyone, members read only themselves
}
function readUser(viewer, id, ifNoneMatch = null) {
// TODO: 404 when missing or not allowed (same answer for both)
// TODO: compute the ETag, answer 304 when it equals ifNoneMatch
// TODO: otherwise return 200 with the public view
}Expected: Five lines print: Bob reading himself 200, reading again 304 with no body, Bob reading Carol 404, a missing id 404, and Alice reading Carol 200 with ETag "v3".
Show hint
Find the target first, then check !target || !canRead(viewer, target) in one condition so missing and not-allowed give the same answer. Do not include a body at all in the 304 result.
Show solution
const user = (n, name, role, version = 1) => ({
id: "u_" + n,
name,
email: name.toLowerCase() + "@example.com",
role,
version,
passwordHash: "not-a-real-hash",
});
const users = [
user(1, "Alice", "admin"),
user(2, "Bob", "member"),
user(3, "Carol", "member", 3),
];
const publicView = ({ id, name, email, role }) => ({ id, name, email, role });
const etagOf = (u) => '"v' + u.version + '"';
// Admins may read everyone; members may read only themselves
const canRead = (viewer, target) => viewer.role === "admin" || viewer.id === target.id;
function readUser(viewer, id, ifNoneMatch = null) {
const target = users.find((u) => u.id === id);
if (!target || !canRead(viewer, target)) {
return { status: 404, body: { error: { code: "user_not_found" } } };
}
const etag = etagOf(target);
if (ifNoneMatch === etag) return { status: 304, etag };
return { status: 200, etag, body: publicView(target) };
}
function show(label, r) {
const body = r.body ? JSON.stringify(r.body) : "(no body)";
console.log(label.padEnd(13), r.status, r.etag ?? "-", body);
}
const [alice, bob] = users;
show("Bob, self", readUser(bob, "u_2"));
show("Bob, again", readUser(bob, "u_2", '"v1"'));
show("Bob, Carol", readUser(bob, "u_3"));
show("Bob, u_99", readUser(bob, "u_99"));
show("Alice, Carol", readUser(alice, "u_3"));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A single resource answers 200 (with an ETag) or 404; a collection uses a { items, next_cursor } envelope with filter, limit and cursor.
- Build responses by picking public fields (an allowlist); never send the database row as it is.
- Check that the resource exists and that this caller may see it for every id; 404 is often better than 403.
- Use ETag with If-None-Match so unchanged data returns a bodyless 304; res.ok is false for 304 and json() must not be called.
RFC 9110 — HTTP Semantics — IETF