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

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.