Skip to content
Advertisement

Specifying sort order direction in a JSON API

Does Restful API define proper ways to give Sort Order Direction, (Ascending or Descending) for API user parameters ?

I am letting a user input a request string, that only allows two options for API to work “Ascending” or “Descending” . Is there a more formal way of doing this per standards?

Request:

{
  "sortField": "PaymentDate",
  "sortOrder": "Descending"
}

Specifying sort order in a JSON API

Advertisement

Answer

The JSON:API specification specifies that sorting order is ascending by default. Client could switch the sorting order by prefixing the sort field with a minus (-).

The sort order for each sort field MUST be ascending unless it is prefixed with a minus (U+002D HYPHEN-MINUS, “-“), in which case it MUST be descending.

https://jsonapi.org/format/1.1/#fetching-sorting

Your example given does not look as if your API implements the JSON:API specification. Even though this question is tagged with [json-api]. If you API does not implement the JSON:API specification, you are free to design the API for controlling sorting order as you like.

The API specification of the OpenStack project could give an inspiration. It also uses a comma-separated list of sorting fields: ?sort=key1,key2,key3. A client may specify the sorting direction by appending either asc or desc to the sorting field using colon (:) as a separator: ?sort=key1:asc,key2:desc,key3:asc. If sorting direction is not specified, then the server can chose sorting direction.

Sorting is determined through the use of the ‘sort’ query string parameter. The value of this parameter is a comma-separated list of sort keys. Sort directions can optionally be appended to each sort key, separated by the ‘:’ character.

The supported sort directions are either ‘asc’ for ascending or ‘desc’ for descending.

The caller may (but is not required to) specify a sort direction for each key. If a sort direction is not specified for a key, then a default is set by the server.

https://specs.openstack.org/openstack/api-wg/guidelines/pagination_filter_sort.html#sorting

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement