Lesson 8 / 27
Filtering, Sorting and Field Selection
Let clients narrow collections and responses with simple, predictable query parameters.
Small, consistent conventions
Use query parameters for filtering (?status=paid&created_after=2026-09-01), sorting (?sort=-created_at,total, where - means descending) and field selection (?fields=id,total) or an expand parameter to embed related resources (?expand=customer) and save round trips. Keep names and formats uniform across all collections, whitelist the fields clients may filter or sort by (and index them), validate values strictly, and document defaults. Avoid inventing a query language unless you truly need it; start simple and extend with new optional parameters, which is a backward-compatible change.
A request using the conventions
One request combines filtering, sorting, field selection and paging. Unknown parameters should produce a clear 400, not be silently ignored.
GET /v2/orders?status=paid&created_after=2026-09-01&sort=-created_at&fields=id,total,customer_id&limit=50
200 OK
{ "data": [ {"id": "ord_91", "total": 1200, "customer_id": "cus_7"}, ... ],
"next_cursor": "eyJhZnRlciI6ICJvcmRfNDIifQ==" }Do not allow unbounded queries
Cap limit, restrict sortable fields to indexed ones and bound date ranges. A single clever request must not be able to scan the whole database.
Quick check: What does `?sort=-created_at` conventionally mean?
- Sort ascending
- Delete created_at
- Sort by created_at descending
- Hide created_at
Answer
Sort by created_at descending — A leading minus is a common convention for descending order.