How to sort the Directus API
The Directus API has a powerful sorting system built into it's core. You can easily sort your results across your available fields. Sorting your data is essential for optimizing your connections. Especially when dealing with a lot of data. In this article I will cover the sort parameter in GraphQL and REST API.
To sort data in the Directus API, simply add the sort parameter and use the Directus Documentation to formulate the desired direction from your available fields.
Sorting in GraphQL
Directus combined with GraphQL is very powerful. The sort parameter can be added to a query to change the order of the returned data. Here is an example that sorts by the date created descending.
query {
articles(
sort: [ "-date_created" ]
) {
id
title
author {
first_name
}
}
}
Note the (-) in front of date_created. This reverses the direction where date_created is the field name.
The GraphQL must be wrapped in JSON so the CURL command looks something like this.
curl -H "Authorization: Bearer your-bearer-token" -X POST -d '{"query": "query { articles(sort: [ "-date_created" ]) { id title author { first_name }}}"}' https://directus.example.com/graphql
If you want to sort with more than one field, simply include the fields within the list. In the example below, I'm sorting by the author first, then the date created.
query {
articles(
sort: [ "author", "-date_created" ]
) {
id
title
author {
first_name
}
}
}
Sorting in REST API
Adding the sort parameter works quite similar. To replicate the same example as above, here is the request URL. Note the format of the sort parameter and the (-) whch reverses the direction of the values.
https://directus.example.com/items/articles?fields=id,title,author.first_name&sort=-date_created
The query in CURL is quite simple since all the parameters are in the URL.
curl -H "Authorization: Bearer your-bearer-token" https://directus.example.com/items/articles?fields=id,title,author.first_name&sort=-date_created
To include a second sort field, simply add the field to the sort values and seperate with a comma.
https://directus.example.com/items/articles?fields=id,title,author.first_name&sort=author,-date_created
Documentation
Use the Directus documentation to see the full list of possibilities.
Conclusion
Sorting your results is very useful for any project, especially when dealing with massive data sources. Be sure to read my other articles on API parameters.