Course contentsShow
← System Design
Lesson 1894 of 1,91945. API Design and VersioningFree lesson

Sorting Query Parameters

Allowing clients to specify sort fields and directions, handling multi-column sorting orders.

Sorting Query Parameters

What you'll learn: How to design query parameters that let clients specify which fields to sort by and in what order, including multi-column sorting.

Why Sorting Matters

After filtering your API results, clients often need them in a specific order—newest first, alphabetically, by price, etc. Rather than forcing a fixed sort order, you expose sort query parameters that give clients control over result ordering.

Basic Syntax

The simplest approach uses a sort parameter with field names:

GET /products?sort=price
GET /users?sort=created_at

To specify direction, you can use prefixes:

GET /products?sort=-price         # descending (minus prefix)
GET /products?sort=+name          # ascending (plus prefix, often default)

Multi-Column Sorting

Real-world needs often require sorting by multiple fields—like sorting users by country first, then by registration date within each country. Support this with comma-separated values:

GET /users?sort=country,-created_at

This means: "Sort by country ascending, then within each country, sort by created_at descending."

Design Considerations

  • Field validation: Only allow sorting on indexed fields to avoid performance issues
  • Default sort order: Define sensible defaults (often ID or creation timestamp)
  • Security: Block sorting on sensitive fields users shouldn't access
  • Documentation: Clearly specify which fields support sorting and default directions

Think of it like a spreadsheet: users click column headers to sort, sometimes holding Shift to add secondary sorts. Your API provides the same flexibility through structured parameters.

Key Takeaway: Sorting query parameters give clients flexible control over result ordering through field names and direction indicators, with multi-column support for complex sorting needs.