Sorting and Ordering Results
What you'll learn: How to let API clients control the order of returned resources using query parameters, including multiple fields and directions.
When your API returns a collection of resources, clients often need them in a specific order—newest first, alphabetically by name, or by priority. Rather than returning data in arbitrary database order, you expose sort parameters that let clients request the ordering they need.
The Basics of Sort Parameters
A common pattern uses a sort query parameter that accepts field names:
GET /products?sort=price
GET /products?sort=name
For descending order, prefix the field with a minus sign:
GET /products?sort=-price (highest price first)
GET /products?sort=-created (newest first)
Multiple Sort Fields
Real-world scenarios often need secondary sorting. Use comma-separated values:
GET /products?sort=category,-price
This means: "Sort by category ascending, then by price descending within each category." Think of it like a spreadsheet: primary sort column first, then tie-breakers.
Default Sort Order
Always define a default sort when no parameter is provided. Without one, results may appear random or change unpredictably. Document this clearly:
GET /products
(defaults to: sort=name)
Performance Implications
Sorting impacts database performance. Fields used for sorting should have database indexes, especially on large tables. Allowing arbitrary field sorting can enable expensive queries—consider limiting sortable fields to those that are indexed and commonly needed.
Key Takeaway: Sort parameters give clients control over result ordering through query strings, support multiple fields with direction indicators (like -), require sensible defaults, and need careful index planning to avoid performance issues.