JsonApi.org compability package for Laravel 5.5+
This package is intended to provide an easy way to achieve compatibility with the API standards defined at http://jsonapi.org.
Currently, only the top-level structure (http://jsonapi.org/format/#document-top-level) is supported,
but ongoing work strives for a more complete coverage of the standard., (*1)
How to install it
You can install the package via composer.
For Laravel 5.5 up to 6.x run:, (*2)
$ composer require bitnetic/jsonapi "0.1.*"
For Laravel 7 run:, (*3)
$ composer require bitnetic/jsonapi "^2.0"
JsonApi comes with a config file named config/jsonapi.php.
This file is deployed to the central laravel configuration directory using the vendor:publish command:, (*4)
$ php artisan vendor:publish --provider "Bitnetic\JsonApi\JsonApiServiceProvider"
Next, extend your exception handler with JsonApi standard responses.
Note that this example uses the Laravel 7 signature that uses Throwable
instead of Exception
that was used in Laravel 5 and 6., (*5)
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Throwable $exception)
{
return JsonApiExceptionHandler::render($request, $exception)
?? parent::render($request, $exception);
}
How to use it
This JsonApi package is minimal-invasive to Laravel.
Just use HTTP resources within your controllers and extend them from JsonApiResource
., (*6)
This is an example controller method:, (*7)
/**
* @return UserResource
*/
public function getUser(Request $request)
{
return new UserResource($request->user());
}
You can also use collections in a list()
-method by calling UserResource::collect($myUsers);
., (*8)
You can always add your own data into the meta
or errors
field, or return a different HTTP status code.
The package just makes sure that the status code is mapped additionally as a status
field within the meta block., (*9)
return new UserResource($myUser, ['type' => 'admin'], $exception->errors(), 404);
How to write an appropriate resource
Take a look at the following example:, (*10)
class UserResource extends JsonApiResource
{
public function toArray($request)
{
return [
'name' => $this->name,
'email' => $this->email,
'password' => $this->when(
$request->user() ... e.g.,
MySecureTokenFactory::wrap($this->password),
];
}
}
In a resource like UserResource($user)
, you can access the underlying user object by using $this
., (*11)
You can also take a look the included ExampleResource
and adopt it to your needs., (*12)
The outcome
The formatted Json-Api-Response from the examples above should produce something like this:, (*13)
{
"data": {
"name": "John Doe",
"email": "john@example.com"
},
"meta": {
"status": 200
"success": true
}
}