How to sort included resources?


#1

What is the best way to to go about sorting included resources?

If hitting the endpoint /allTheObjects?sort=-name&include=theOtherObjects, how would we apply a sort of createDate to the collection of theOtherObjects ?

Thanks very much for any input and advice.


#2

The "included" collection can come from many different relationship paths and resources, so it usually doesn’t make sense to sort it, and there’s no built-in way to doing so. However, JSON API does let you define query parameters unique to your API, so you could easily define one that performs this feature.

API-specific query parameters have to include at least one non–[a-z] character, so that JSON API can define new query parameters in the future without the risk of them clobbering your own. And a query parameter can’t do anything that violates a requirement of the base spec, but sorting "included" is definitely allowed.

So, I’d define a parameter called sort-included and have it use the same syntax as the standard sort parameter, and that should do it!


#3

Thanks so much for the reply, I’ll give that a try!


#4

@blukes You might consider using multiple “?” in the URI which is allowed: http://stackoverflow.com/a/2924187/933711

/allTheObjects?sort=-name&include=theOtherObjects?sort=-date,evenMoreObjects?sort=+amount

This way you could sort each included set by specific parameters.

@ethanresnick Chime in if you have any thoughts on this approach.


#5

@andrewhenderson The feature you’re proposing could definitely be useful, and you’re right that having multiple question marks is valid in a URI’s query string. But having question marks as part of the ?include parameter’s value in JSON API is not. From the spec:

The value of the include parameter MUST be a comma-separated (U+002C COMMA, “,”) list of relationship paths. A relationship path is a dot-separated (U+002E FULL-STOP, “.”) list of relationship names.

Also, the same resource can be linked from multiple relationships, but it’ll only show up in "included" once (that’s the point), so you’d have to define how to handle this case. For example, imagine a request like GET /articles?include=author,editor where the same person is sometimes an author and sometimes an editor; which rules should this person be sorted under?

But I guess the bottom line here is that the spec gives each API total freedom to define whatever query parameter(s) it wants (as long as they contain a non-a to z character) to sort the included collection however it wants.