Preserving Order of Related Resources

Hello everyone,

I’m working on an application where the order of related resources in a JSON array has semantic importance. It doesn’t look like there’s any word on this within the spec so I want to ask here. I’m wondering about the default sort order that the API should return objects in. I would like and kind of expect them to be returned in the same order that the client created them in. Specifically, I want to ensure that clients retrieve related resources in the exact order they created, updated or added them. Before finalizing this approach, I’d like to gather insights and feedback from the community.

  1. Consistency: Is it common practice in the JSON:API community to preserve the order of related resources? Are there any challenges or pitfalls I should be aware of?
  2. Storage and Retrieval: For those who have implemented such an order-preserving system, how did you handle it at the database level? Especially in contexts where the storage mechanism might not natively support order preservation.

Any advice, experiences, or insights would be greatly appreciated!

Thank you in advance.

The JSON:API specification keeps it up to each implementation if the order of related resources has a meaning. It’s discussed in this note in Resource Linkage section:

The spec does not impart meaning to order of resource identifier objects in linkage arrays of to-many relationships, although implementations may do that. Arrays of resource identifier objects may represent ordered or unordered relationships, and both types can be mixed in one response object.

Please note that this has some limitations though:

  1. The sort query parameter defined by JSON:API specification does not support sorting if related resources. It only supports sorting of the primary data. An extension is needed of clients should control sorting order.
  2. Clients can update the sorting only using a full-replacement. Full replacement of to-many relationships increases the risk of collisions when multiple clients updating the same relationship of a resource at the same time.
1 Like