Lesson 11 / 25

Filtering & Sorting

Let clients filter and sort collections with query parameters, and reject unknown fields with 400 errors.

Query parameters, not new endpoints

Keep one endpoint per resource; let query params narrow it down instead of creating /orders/pending and /orders/byCustomer.

GET /orders?status=pending
GET /orders?customerId=9&status=shipped
GET /orders?minTotal=500&sort=-createdAt
GET /orders?sort=status,-createdAt

A sort convention

A common convention: sort=field for ascending, sort=-field for descending, comma-separated for multiple keys. Document exactly which fields are sortable and filterable — not every column should be.

Validate, don't trust

Reject unknown filter fields or sort keys with 400 Bad Request rather than silently ignoring them — a typo shouldn't quietly return the wrong data.