Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Designing Resources and Endpoints

Filtering, Sorting and Query Parameters

Design query parameters for REST collections: filters, search, sorting with a safe whitelist, sparse fieldsets and limits, with a runnable server and parser.

A collection like /products quickly grows to thousands of items. Clients rarely want all of them: they want the red ones, the cheapest first, or just the names. The standard answer is query parameters: optional key=value pairs after the ? that refine what a GET returns without creating a new URL for every combination.

Because the path identifies the resource and the query shapes the view of it, filtering and sorting stay on GET /products instead of becoming /products/red/cheapest-first.

Filtering

The simplest filter is the field name as a parameter:

HTTP
GET /products?category=shoes&inStock=true

Several values for the same field usually mean OR: ?color=red,blue or ?color=red&color=blue. Choose one style and keep it.

For ranges and comparisons, two popular conventions:

HTTP
GET /products?minPrice=1000&maxPrice=5000
GET /products?price[gte]=1000&price[lte]=5000

The second packs the operator into the key (gte, lte, gt, lt, ne). It scales better when many fields need ranges. Whichever style you pick, apply it to every collection.

For free text, a single q parameter is typical: GET /products?q=running+shoes. Behind it you might have a database LIKE, a full-text index or a search engine.

Sorting

Use one sort parameter that lists fields in priority order, with a leading minus for descending:

HTTP
GET /products?sort=-price,name

This means "price descending, then name ascending". It is compact, easy to extend and used by many public APIs.

Sparse fieldsets and expansion

Large objects waste bandwidth, especially on mobile. Let clients ask for just the fields they need:

HTTP
GET /products?fields=id,name,price

The opposite problem is related data: instead of making a second request for the product's brand, let clients ask for it to be embedded with ?include=brand (or expand=brand). Relationships and actions returns to this.

Limits come first

Every collection endpoint must have a maximum page size, otherwise one request can return a million rows. A minimal version is ?limit=20, with a server-side cap (for example 100) and a sensible default. The full story, with offset and cursor pagination, is in the pagination lesson.

Never trust the query string

Query parameters come straight from the client, so they can be anything. The golden rule: only allow what you explicitly list.

  • Sorting by a field name taken from the URL and pasted into SQL (ORDER BY ${sort}) is a classic injection hole. Compare against an allow-list of sortable columns instead.
  • Unknown filter names should be ignored or rejected with 400; decide, then be consistent. Rejecting catches typos (?colour=red silently returning everything is a bug magnet).
  • Parse numbers and booleans explicitly; ?limit=abc should give 400, not NaN rows.
  • Cap the length of search strings and the number of values.

An API with filters, sorting and fields

The server below implements all four ideas on an in-memory list. A small parseQuery function validates the parameters against an allow-list and returns either a clean query or a list of problems.

Node.js Filter, sort and select fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last two requests show why validation matters: a typo (colour) and a bad limit produce a clear 400 with a list of problems instead of silently wrong data.

Encoding and special characters

Characters like &, =, spaces and non-ASCII letters must be percent-encoded in query values. Never build query strings by concatenation; use URLSearchParams, which handles it:

Node.js Building query strings safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A consistent vocabulary

Document your parameter names once and reuse them across the whole API: q, sort, fields, include, limit, cursor or page. An API where /orders uses sort but /invoices uses order_by forces every client developer to read two sets of docs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a sort parameter such as sort=-price,name order results?

    The leading minus means descending, and fields are applied in the order listed.
  2. 2. Why should sort fields be compared against an allow-list?

    Only explicitly supported columns should ever reach your query builder.
  3. 3. What should an API do with an unknown filter parameter such as colour?

    Rejecting catches typos; ignoring is lenient. Either is valid if consistent.
  4. 4. Which JavaScript tool should build query strings with special characters?

    URLSearchParams percent-encodes keys and values correctly.

Summary

  • Use query parameters to shape a collection view: filters, q for search, sort, fields, include and limit.
  • A leading - in sort means descending; multiple fields are comma separated.
  • Always cap limit and validate every parameter against an allow-list.
  • Reject or ignore unknown parameters consistently, and answer invalid values with 400.
  • Build query strings with URLSearchParams and keep the vocabulary identical across all endpoints.

Next: Error Responses