When building a RESTful API we often want to give consumers the option to order collections in a specific way (e.g. ordering users by last name). If our API supports pagination this can be quite an important feature. When clients only query a specific part of a collection they are unable to order elements on the client.
Sorting is typically implemented via Query-Parameters. In the next section we look into common ways to sort collections and a few things we should consider.
Sorting by single fields
The easiest way is to allow sorting only by a single field. In this case, we just have to add two query parameters for the field and the sort direction to the request URI.
For example, we can sort a list of products by price using:
asc and desc are usually used to indicate ascending and descending ordering.
We can reduce this to a single parameter by separating both values with a delimiter. For example:
As we see in the next section, this makes it easier for us to support sorting by more than one field.
Sorting by multiple fields
To support sorting by multiple fields we can simply use the previous one-parameter way and separate fields by another delimiter. For example:
It is also possible to use the same parameter multiple times:
Note that using the same parameter multiple times is not exactly described in the HTTP RFC. However, it is supported by most web frameworks (see this discussion on Stackoverflow).
Checking sort parameters against a white list
Sort parameters should always be checked against a white list of sortable fields. If we pass sort parameters unchecked to the database, attackers can come up with requests like this:
Yes, this would possibly not be a real issue if passwords are correctly hashed. However, I think you get the point. Even if the response does not contain the field we use for ordering, the simple order of collection elements could lead to unintended data exposure.