Sorting API content
As we have seen so far, Strapi provides us with defaults that allow us as developers to speed up some of the common tasks with minimal effort. A common task when dealing with API content is sorting data according to a specific field.
To sort the data, we can use the sort
parameter followed by the field we want to sort on and the direction of the sort. The general format is ?sort=FIELD_NAME:[ASC OR DESC]
.
To illustrate how the sort
parameter works, let's assume we have the following requirement:
As an API user I want to be able to sort the classrooms by the maximum number of students from the largest to the smallest
To satisfy this requirement, we will use the sort
API parameter on maxStudents
; the API URL will be GET /api/classrooms?sort=maxStudents:desc
. Let's test it with Postman; we should see the classrooms sorted by the highest maxStudents
number first: