I'd like to build an API that adheres to the JSONAPI standard.
So I'm using Collections and Resource classes to return a structured response.
When I return a collection I'm told here to have two parent items, links and data. So I'm making my ResourceCollection look like this:
/api/v1/posts
return [
'links' => [
'self' => url()->current(),
],
'data' => $this->collection,
];
Returns:
{
"links": {
"self": "http:\/\/localhost\/api\/v1\/installations"
},
"data": [
{
"type": "installations",
"id": 1,
...
Good.
By using $this->collection I'm automatically calling my Resource class. This is a nice feature, but the format differs from when I would call that resource directly (e.g. /api/v1/posts/1).
The code of Resource class
return [
'links' => [
'self' => url()->current(),
],
'data' => [
'type' => 'installations',
'id' => $this->id,
'attributes' =>
[
'title' => $this->title,
],
'relationships' =>
[
//
]
]
];
Calling that directly works nicely, BUT now my Collection class is "messed up" (below).
I don't want the links showing for the Resource class when called via the Collection class and no repetition of the data element. The parent data should just include objects.
{
"links": {
"self": "http:\/\/localhost\/api\/v1\/installations"
},
"data": [
{
"links": {
"self": "http:\/\/localhost\/api\/v1\/installations"
},
"data": {
"type": "installations",
"id": 1,
"attributes": {
"title": "MOOS Office"
},
}
}
]
}
Is there any way I can alter the Resource class depending on how it's called? Anyone got best practice experience here?