Consider an API endpoint that returns a list of users sorted by age ascending when called with ?sort=age. What will be the order of user IDs in the response?
GET /users?sort=age
Response JSON:
[
{"id": 3, "name": "Alice", "age": 22},
{"id": 1, "name": "Bob", "age": 25},
{"id": 2, "name": "Charlie", "age": 30}
]Sorting by age ascending means the youngest user comes first.
The API sorts users by their age in ascending order, so the user with age 22 (id 3) comes first, then age 25 (id 1), then age 30 (id 2).
You want to get a list of products sorted by their name in reverse alphabetical order using a REST API. Which sort parameter value should you use?
Many APIs use a minus sign before the field name to indicate descending order.
The common convention is to prefix the field with a minus sign to sort descending, so sort=-name sorts by name descending.
An API call GET /items?sort=price,desc returns a 400 Bad Request error. What is the likely cause?
Check the API documentation for the expected format of the sort parameter.
The API expects the sort parameter to be a single field name optionally prefixed by a minus sign for descending order. Using a comma is invalid syntax.
An API supports sorting by multiple fields separated by commas. Given the call GET /books?sort=author,title, what is the order of books?
Books data:
[
{"author": "Smith", "title": "Zebra"},
{"author": "Smith", "title": "Apple"},
{"author": "Adams", "title": "Banana"}
]
Sorted by author ascending, then title ascending.Sorting by multiple fields means sorting by the first field, then by the second field within ties.
The books are sorted first by author ascending: Adams before Smith. For books with the same author (Smith), they are sorted by title ascending: Apple before Zebra.
You are building a REST API that returns a list of products. You want to add a sort query parameter that supports sorting by one or more fields, each optionally descending with a minus sign prefix. Which approach correctly implements this?
Think about how to handle multiple fields and descending order indicated by a minus sign.
The best approach is to parse the sort parameter by commas, detect descending order by a minus sign prefix, and apply sorting accordingly for each field in order.