Related resources relationship attributes

#1

Hi! I am starting a new project and I am trying to adapt our API to JSON API since it seems like a good specification of how a JSON API would follow a predictable pattern. I have one problem that I cannot seem to solve though, currently in the example in the home page of https://jsonapi.org/ the example shows the /articles request with the author, comments and comments.author included.

Now, the main issue comes when you look a bit deep into that, the related resources in the /articles resource are comments and authors. There’s also the relationship to comments which is comments.author which was also described in the sample. Now the only missing part is: How do you get the attributes of the author of the comments? Can you just add them to the relationship keyword under comments? That seems unlikely because relationships are the same across both resources (related and main) with only type and id attributes. Do you put them in includes keyword? That also seems unlikely because that would mix up the main resources relationships that you’re asking for. My final thought was it has to follow the link in the relationship to get the data for comments.author, am I correct assuming that or is any of the other 2 solutions a valid JSON API solution?

0 Likes

#2

Your second and third thoughts are correct.

You don’t have to supply the attributes of the comment’s author, you can leave it up to the client to fetch it. Although it would be nice to supply the url to do so (which the example on jsonapi.org’s homepage doesn’t do).

But if you want to supply the attributes of the comment’s authors, they should end up in the included array. The spec states it as (emphasis mine) “an array of resource objects that are related to the primary data and/or each other”. It shouldn’t really matter that the included array is a mix of direct and indirect relationships (you can even add unrelated ones under certain circumstances). By checking the relationships of each resource you should be able to figure out how an included resource is related to the others. Also note person 9 from the example, it is related to both the main and a related resource.

(The first thought you mentioned, of adding attributes in the relationship, is indeed not allowed. It should be resource identifier objects only there.)

0 Likes

#3

Hi Ahmed,

At the risk of tooting my own horn and/or being flamed, please take a look at https://columbia-it-django-jsonapi-training.readthedocs.io which is some training material I put together for internal developers here. Since “sharing is caring” I’ve made it public (and would happily accept feedback and pull requests).

It’s a work-in-progress, currently focusing on improving documentation and “Try it out” functionality with a Swagger/OAS 3.0 example spec that is derived from the jsonapi json-schema.org schema doc.

0 Likes