I am trying to build an API in rails using JSON API specification
My User model has change objects associated with them. For example, user can have the following change:
{
id: 10,
type: 'changes',
diffs: [
{
subject: 'email',
from: 'old@example.org',
to: 'new@example.org'
},
{
subject: 'tags',
from: []
to: [{ id: 1, type: 'tags', label: 'Ruby' }]
}
]
}
As you can see the diffs
property contains an array of change differences and the second difference is an array of objects difference. I would want to modify this format (if possible) so it will conform JSON API specification. Like this:
{
subject: 'tags',
from: []
to: [{ id: 1, type: 'tags' }]
}
And put the tag's attributes into the included section:
included: [
{
id: 1,
type: 'tags',
attributes: { label: 'Ruby' }
}
]
Question: differences is an array of objects (not records, they do not have ID) which contain fields with records. Is possible to format the response so deeply nested records (like tags in my case) will be reference to the records in the included section?
I would want to use fast_jsonapi gem
I don't think you can do this without violating the spec.
A resource object must contain an id:
“Resource objects” appear in a JSON API document to represent resources.
A resource object MUST contain at least the following top-level members:
- id
- type
There is only one exception allowed by spec:
Exception: The id member is not required when the resource object originates at the client and represents a new resource to be created on the server.
So if your diffs
don't have an ID you can't model them as a resource object.
But you are not allowed to include a resource that is not referenced by a resource object:
Compound documents require “full linkage”, meaning that every included resource MUST be identified by at least one resource identifier object in the same document. (source)
There is only one exception that does not apply to the case discussed here:
The only exception to the full linkage requirement is when relationship fields that would otherwise contain linkage data are excluded via sparse fieldsets.