When I build an API I typically use a pretty simple format. It is actually pretty much Fractal out of the box by way of Spatie's Larave Fractal package. Personally, I've found other formats more verbose than I need. I've built some pretty robust APIs using this format without issue. I also rely heavily on sending status codes for request status and consumer notification.
When building an app that consumes the API I typically build SDKs. I've been using Apiary to document my APIs and you get a pretty nice tool set from them, making SDK generation and testing so much easier.
The responses were built using the following code:
routes/api.php
<?php
use App\User;
use Illuminate\Http\Request;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
function transformer($user)
{
return [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
];
}
Route::get('/users/{user}', function (User $user) {
return fractal()
->item($user)
->transformWith('transformer')
->respond();
});
Route::get('/users', function () {
$usersPaginator = User::paginate(3);
return fractal()
->collection($usersPaginator->getCollection())
->transformWith('transformer')
->paginateWith(new IlluminatePaginatorAdapter($usersPaginator))
->respond();
});
{
"data": {
"id": 1,
"name": "Dayna Lesch DDS",
"email": "[email protected]"
}
}
{
"data": [
{
"id": 1,
"name": "Dayna Lesch DDS",
"email": "[email protected]"
},
{
"id": 2,
"name": "Damion Robel",
"email": "[email protected]"
},
{
"id": 3,
"name": "Benedict Streich",
"email": "[email protected]"
}
],
"meta": {
"pagination": {
"total": 10,
"count": 3,
"per_page": 3,
"current_page": 1,
"total_pages": 4,
"links": {
"next": "http:\/\/localhost:8000\/api\/users?page=2"
}
}
}
}
Do you always use
data
as your root property?