Filter & Sort — API

A filter picks which rows come along, and a sort sets their order. The client sends both in the query string (the part of the URL after ?), such as…

On a marketplace you tick "In stock" and pick the "Highest price" order. The product list changes, and so does the URL in the address bar: a ? followed by your choices. Those choices go to the API, and the API does the filtering and sorting.

The part of the URL after the ? is the query string. At the Bookshop, a client who wants only Andrea Hirata's books, most expensive first, sends GET /books?author_id=1&sort=price&order=desc. A filter picks which rows come along (here: only the books of author number 1). A sort sets their order (here: by price, highest first). It's like asking a shop assistant: "only the Andrea Hirata ones, sorted from the most expensive". The assistant is the API, and it only serves the choices on its list. Sorting by title, price or stock is fine. Sorting by what the shop paid (the cost price) is not, because that is the shop's secret.

Reading the query string

Express splits the query string by name and puts it in req.query. Its values are always text, and a parameter that wasn't sent is undefined:

Request req.query
GET /books {}
GET /books?author_id=1 { author_id: "1" }
GET /books?author_id=1&sort=price&order=desc { author_id: "1", sort: "price", order: "desc" }

Laravel is the same. GET /api/students?class=XII is read in the controller (the Laravel code that handles a request, like a handler in Express) with $request->query('class'), which gives "XII".

Filter: one condition at a time

Every filter that's sent adds one condition to the WHERE, the part of the query that picks rows. A filter that isn't sent adds nothing. The code below collects the conditions in two arrays: where for the condition text, and params for the values.

const where = [];
const params = [];
if (req.query.author_id) {
  where.push("author_id = ?");
  params.push(Number(req.query.author_id));
}
if (req.query.in_stock === "1") {
  where.push("stock > 0");
}
const whereSql = where.length ? " WHERE " + where.join(" AND ") : "";

The results for the Bookshop's 8 books:

Query string The WHERE it builds params Number of books
(empty) (none) [] 8
?author_id=1 WHERE author_id = ? [1] 3
?in_stock=1 WHERE stock > 0 [] 6
?author_id=2&in_stock=1 WHERE author_id = ? AND stock > 0 [2] 1

Sort: a column name can't go through a placeholder

SQL sets the order with ORDER BY. The problem is that a placeholder only fills in values. ORDER BY ? with the value "price" means "sort by the text 'price'", and that text is exactly the same on every row. SQLite doesn't raise an error, but it sorts nothing: the result stays in its original order, The Rainbow Troops, This Earth of Mankind, Beauty Is a Wound, and so on.

So the column name has to be written straight into the SQL text. There is only one safe way to do that: an allowlist, a list of allowed names written by the server itself. The sort value from the client is checked against that list first:

const SORTABLE = ["id", "title", "price", "stock"];
const { sort = "id", order = "asc" } = req.query;
if (!SORTABLE.includes(sort)) {
  return res.status(400).json({ error: "sort must be one of: id, title, price, stock" });
}
if (order !== "asc" && order !== "desc") {
  return res.status(400).json({ error: "order must be asc or desc" });
}
const orderSql = ` ORDER BY ${sort} ${order.toUpperCase()}`;

Why so strict? Without an allowlist, ?sort=cost_price sorts the books by what the shop paid: Edensor (cost 52,000) first, then The Dreamer (55,000). Yet by selling price, The Dreamer (79,000) is the cheapest. The API never sends cost_price, but the order reveals that cost price. The second danger: sort is written straight into the SQL text, so a client can send other content in sort that changes the SQL command. That is SQL injection.

Pages: page and limit

LIMIT (take this many rows) and OFFSET (skip this many rows) hold values, so they may go through placeholders. limit is kept between 1 and 50 with Math.max and Math.min, so a client can't ask for a million rows at once. When the client doesn't send it, limit is 3. One more query counts the total with the same WHERE, for the meta from the Pagination lesson. Here is the full handler:

const SORTABLE = ["id", "title", "price", "stock"];

app.get("/books", (req, res) => {
  const { author_id, in_stock, sort = "id", order = "asc" } = req.query;
  if (!SORTABLE.includes(sort)) {
    return res.status(400).json({ error: "sort must be one of: id, title, price, stock" });
  }
  if (order !== "asc" && order !== "desc") {
    return res.status(400).json({ error: "order must be asc or desc" });
  }
  const page = Math.max(parseInt(req.query.page, 10) || 1, 1);
  const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 3, 1), 50);

  const where = [];
  const params = [];
  if (author_id) {
    where.push("author_id = ?");
    params.push(Number(author_id));
  }
  if (in_stock === "1") where.push("stock > 0");
  const whereSql = where.length ? " WHERE " + where.join(" AND ") : "";

  const { total } = db.prepare("SELECT COUNT(*) AS total FROM books" + whereSql).get(...params);
  const data = db
    .prepare(`SELECT id, title, author_id, price, stock FROM books${whereSql} ORDER BY ${sort} ${order.toUpperCase()} LIMIT ? OFFSET ?`)
    .all(...params, limit, (page - 1) * limit);

  res.json({ data, meta: { page, limit, total, totalPages: Math.ceil(total / limit) } });
});

.all(...params, limit, (page - 1) * limit) fills the placeholders in order: the values in params first (... spreads the array's items one by one), then limit, then the offset.

GET /books?author_id=1&sort=price&order=desc is answered with Andrea Hirata's three books, most expensive first: The Rainbow Troops (89,000), Edensor (85,000), The Dreamer (79,000), plus "meta": { "page": 1, "limit": 3, "total": 3, "totalPages": 1 }.

For GET /books?in_stock=1&sort=title&page=2, 6 books match the filter and limit is 3, so totalPages is 2. Page 2 holds The Dancer, The Dreamer and The Rainbow Troops.

📌 In Laravel

In Laravel, the class filter and a sort with an allowlist look like this:

$class = $request->query('class');
$sort = $request->query('sort', 'id');
abort_unless(in_array($sort, ['id', 'name', 'student_number'], true), 400, 'sort must be one of: id, name, student_number');
$order = $request->query('order') === 'desc' ? 'desc' : 'asc';

$students = Student::when($class, fn ($q) => $q->where('class', $class))
    ->orderBy($sort, $order)
    ->paginate(15);

⚠️ Filters and sorts that leak or quietly go wrong

TL;DR: A filter picks which rows come along, and a sort sets their order. The client sends both in the query string (the part of the URL after ?), such as ?author_id=1&sort=price&order=desc. Express puts them in req.query (in Laravel $request->query('class')), and all their values are text. Every filter adds one condition to the WHERE (the part of the query that picks rows), with its value through a placeholder ?. A column name for ORDER BY (the part of the query that sets the order) can't go through a placeholder: ORDER BY ? sorts nothing. So sort is checked against an allowlist, a list of allowed columns (["id", "title", "price", "stock"]), and order must be asc (ascending) or desc (descending). Anything else is answered 400. Without an allowlist, sort=cost_price leaks the cost price through the order, and orderBy($column) in Laravel with a column name from the client allows SQL injection or access to a sensitive column. For pages, use LIMIT ? OFFSET ? plus meta. In Laravel, when($class, ...) adds a filter only when the parameter is there.

⚡ The client's choices travel in the query string

Meaning: The client sends its filter choices (which rows come along) and sort choices (their order) in the query string, the part of the URL after ?. For example, GET /books?author_id=1&sort=price&order=desc asks for the books of author number 1, most expensive first. Express puts them in req.query, and all their values are text. In Laravel, GET /api/students?class=XII is read with $request->query('class').

⚡ Filters: one condition at a time

Meaning: Every filter that's sent adds one condition to the WHERE (the part of the SQL query that picks rows), with its value through a placeholder ?. A filter that isn't sent adds nothing. The filter ?in_stock=1 (only books that are in stock) is checked with === "1", not for truthiness. The reason: ?in_stock=false gives the text "false", and even that text is truthy.

⚡ Column names go through an allowlist

Write:

const SORTABLE = ["id", "title", "price", "stock"];
const { sort = "id", order = "asc" } = req.query;
if (!SORTABLE.includes(sort)) {
  return res.status(400).json({ error: "sort must be one of: id, title, price, stock" });
}
Guess first: ORDER BY sets the order of rows in SQL. ORDER BY ? is filled with the value "price" through a placeholder. Are the books sorted by price?

No. A placeholder only fills in values, so what gets sorted is the text "price", the same on every row. SQLite raises no error, but the order stays as it was.

Meaning: A column name has to be written straight into the SQL text, so check sort first against SORTABLE: an allowlist (a list of allowed names) the server wrote. "id" and "asc" are the defaults when the client doesn't send sort or order, and a value outside the list is answered 400. Without an allowlist, ?sort=cost_price leaks the cost price through the order, and other values of sort can become SQL injection.

What you will learn