Sorting in a REST API

Sharing is Caring

Sorting is determining the order of items when a list of items is returned from a particular endpoint. The best practice is to really keep things simple and consistent.

When an endpoint returns a lot of data – sorting becomes really important especially if there’s many pages of data and a user might need to read through multiple pages.

Where it makes sense I like to enable sorting by a query string parameter called “sort_by” and a second quarter string parameter called “order_by”.

Assume we have an API designed for a book sort, and we want to sort the list of books by Title and have Z first. We would make an API query to a URL like this:

I don’t implement sorting on every endpoint, because a lot of the time an endpoint will return only a few records OR maybe only one record. There’s quite a bit of overhead to implementing this in each endpoint: the query has to be manually built or manipulated (Look at an ORM to make this easier), and the sort by parameter needs to be validated as existing or the query will fail and probably return a 500 error.
Sharing is Caring

Leave a Reply

Your email address will not be published.