Search code examples
jsonrestjson-api

JSON API identifiers for nested resources relative to parent


When one models resource relationships, the classic example give is for articles and comments. This becomes simple to model because:

  • articles can be uniquely identified: /articles/1
  • comments can be uniquely identified: /comments/2
  • their relationship can be provided as /articles/1/comments which would return only comments for that article

But how does one handle the case where the related resource only exists within the context of the parent?

For example, order and items:

  • order can be uniquely identified /orders/123
  • the items in that order only exist as /orders/123/items
  • and NOT as /items

In JSON-API the relationship object needs a "type" and "id" to specify the linkage:

"relationships": {
    "links": {
        "self": "http://example.com/orders/123/relationships/items",
        "related": "http://example.com/orders/123/items"
    },
    "data": {
        "type": <what goes here>,
        "id": <what goes here>
    }
}

The type and id for data would need to be relative to order number 123. Assuming, of course, that they don't get assigned a UUID or similar from a database because they are, in fact, a composite key. They exist primarily as a foreign key combination.

How does one handle that?

One option for the relation is to use type as order_item and id as a hash or something delimited string concatenation of the order's id and the item's id. (e.g. 123_abc). 123 I get from the order and abc I get from the item in the order.

Is there another way other than avoiding the need altogether to supply resource linkage?


Solution

  • Every resource must be uniquely identified by a combination of type and id according to JSON API specification:

    Identification

    Every resource object MUST contain an id member and a type member. The values of the id and type members MUST be strings.

    Within a given API, each resource object’s type and id pair MUST identify a single, unique resource. (The set of URIs controlled by a server, or multiple servers acting as one, constitute an API.)

    https://jsonapi.org/format/#document-resource-object-identification

    Therefor you are not only requiring an ID for resource linkage but also to build any valid response including such a resource.

    But there are no rules about how you generate that unique IDs per type. Combining an unique order ID with an unique item ID to get an unique ID per item in an order seems to be a fine approach if your data model doesn't include an ID.