Enterprise Java

REST: Sorting collections

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:

1
GET /products?sort=price&order=asc

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:

1
GET /products?sort=price:asc

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:

1
GET /products?sort=price:asc,name:desc

It is also possible to use the same parameter multiple times:

1
GET /products?sort=price:asc&sort=name:desc

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:

1
GET /users?sort=password:asc

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.

Published on Java Code Geeks with permission by Michael Scharhag, partner at our JCG program. See the original article here: REST: Sorting collections

Opinions expressed by Java Code Geeks contributors are their own.

Michael Scharhag

Michael Scharhag is a Java Developer, Blogger and technology enthusiast. Particularly interested in Java related technologies including Java EE, Spring, Groovy and Grails.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
St1mpy
St1mpy
3 years ago

Never read such a bad article, even here

Back to top button