Laravel 5 JSON API Transformer Package
Compatible with Laravel 5.0, 5.1 & 5.2
Use Composer to install the package:
composer require nilportugues/laravel5-json-apiNow run the following artisan command:
php artisan vendor:publishFor the sake of having a real life example, this configuration will guide you on how to set up 7 end-points for two resources, Employees and Orders.
Both Employees and Orders resources will be Eloquent models, being related one with the other.
Furthermore, Employeeswill be using an Eloquent feature, appended fields to demonstrate how it is possible to make the most of Eloquent and this package all together.
Open up config/app.php and add the following line under providers array:
'providers' => [
//...
NilPortugues\Laravel5\JsonApi\Laravel5JsonApiServiceProvider::class,
],We will be planning the resources ahead its implementation. All routes require to have a name.
This is how our app/Http/routes.php will look:
'Api'], function() {
Route::resource('employees', 'EmployeesController');
Route::get(
'employees/{employee_id}/orders', [
'as' => 'employees.orders',
'uses' => 'EmployeesController@getOrdersByEmployee'
]);
});
//...First, let's define the Models for Employees and Orders using Eloquent.
Employees (Eloquent Model)
hasMany(Orders::class, 'employee_id')->limit(10);
}
/**
* @return string
*/
public function getFullNameAttribute()
{
return $this->first_name.' '.$this->last_name;
}
}
Employees SQL
…Orders (Eloquent Model)
belongsTo(Employees::class, 'employee_id');
}
}Orders SQL
…Follow up, we'll be creating Transformers. One Transformer is required for each class and it must implement the \NilPortugues\Api\Mappings\JsonApiMapping interface.
We will be placing these files at app/Model/Api:
EmployeesTransformer
…Same goes for Orders, these files will also be placed at app/Model/Api:
OrdersTransformer
['name' => 'orders.show', 'as_id' => 'id'],
'employee' => ['name' => 'employees.show', 'as_id' => 'employee_id'],
];
}
/**
* {@inheritDoc}
*/
public function getRelationships()
{
return [];
}
/**
* List the fields that are mandatory in a persitence action (POST/PUT).
* If empty array is returned, all fields are mandatory.
*/
public function getRequiredProperties()
{
return [];
}
} Create file config/jsonapi.php. This file should return an array returning all the class mappings.
register(\NilPortugues\Laravel5\JsonApi\Laravel5JsonApiServiceProvider::class);
$app->configure('jsonapi');Also, enable Facades by uncommenting:
$app->withFacades();We will be planning the resources ahead its implementation. All routes require to have a name.
This is how our app/Http/routes.php will look:
…Same as Laravel 5.
Same as Laravel 5.
Whether it's Laravel 5 or Lumen, usage is exactly the same.
Let's create a new controller that extends the JsonApiController provided by this package, as follows:
Lumen users must extends from LumenJsonApiController not JsonApiController.
…And you're ready to go. Yes, it is THAT simple!
This is the output for EmployeesController@getAction being consumed from command-line method issuing: curl -X GET "http://localhost:9000/employees/1".
Output:
HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+json…POST requires all member attributes to be accepted, even those hidden by the mapper.
For instance, attachments member was hidden, but it is required, so it needs to be passed in with a valid value. On the other hand, full_name member value must not be passed in as an attribute or resource creation will fail.
Passing and id is optional and will be used instead of a server-side generated value if provided.
Sending the following data to the server using POSTto the following URI http://localhost:9000/employees:
…Will produce:
HTTP/1.1 201 Created
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+json
Location: http://localhost:9000/employees/10Notice how 201 HTTP Status Code is returned and Location header too. Also attachments is not there anymore, and full_name was displayed.
…PUT requires all member attributes to be accepted, just like POST.
For the sake of this example, we'll just send in a new job_title value, and keep everything else exactly the same.
It's important to notice this time we are required to pass in the id, even if it has been passed in by the URI, and of course the id values must match. Otherwise it will fail.
Sending the following data to the server using PUTto the following URI http://localhost:9000/employees/10:
…Will produce:
HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+json…PATCH allows partial updates, unlike PUT.
We are required to pass in the id member, even if it has been passed in by the URI, and of course the id values must match. Otherwise it will fail.
For instance, sending the following data to the server using the following URI http://localhost:9000/employees/10:
{
"data": {
"type": "employee",
"id": 10,
"attributes": {
"email_address": "[email protected]"
}
}
}Will produce:
HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+json…DELETE is the easiest method to use, as it does not require body. Just issue a DELETE to http://localhost:9000/employees/10/ and Employee with id 10 will be gone.
It will produce the following output:
HTTP/1.1 204 No Content
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/vnd.api+jsonAnd notice how response will be empty:
According to the standard, for GET method, it is possible to:
fieldsquery parameter.For instance, passing /employees/10?fields[employee]=company,first_name will produce the following output:
…include resources by passing in the relationship between them separated by dot, or just pass in list of resources separated by comma.For instance, /employees?include=order will only load order type data inside include member, but /employees?include=order.employee will only load those orders related to the employee type.
Sort results using sort and passing in the member names of the main resource defined in data[type] member. If it starts with a - order is DESCENDING, otherwise it's ASCENDING.
For instance: /employees?sort=surname,-first_name
For instance: /employees?page[number]=1&page[size]=10
The JSON API allows resource creation and modification and passing in relationships that will create or alter existing resources too.
Let's say we want to create a new Employee and pass in its first Ordertoo.
This could be done issuing 2 POST to the end-points (one for Employee, one for Order) or pass in the first Order as a relationship with our Employee, for instance:
…Due to the existance of this use case, we'll have to ajust our Controller implementation overwriting some methods provided by the JsonApiController: createResourceCallable, updateResourceCallable and patchResourceCallable.
Here's how it would be done for createResourceCallable.
…It is important, in order to use Transactions, do define in Eloquent models the $fillable values.
Here's how Employees and Orders look like with $fillable defined.
Employees (Eloquent Model) with $fillable
hasMany(Orders::class, 'employee_id')->limit(10);
}
/**
* @return string
*/
public function getFullNameAttribute()
{
return $this->first_name.' '.$this->last_name;
}
}
Orders (Eloquent Model) with $fillable
belongsTo(Employees::class, 'employee_id');
}
}Adding custom response headers can be done for multiple reasons: versioning, setting expire headers, caching, setting private or public the served content...
In order to do this, it's as simple as overwriting the JsonApiController addHeaders method. For instance, let's use the EmployeeController as an example:
headers->set('X-API-Version', '1.0');
$response->setPublic();
$response->setMaxAge(60);
$response->setSharedMaxAge(60);
return $response;
}
} Now all supported actions will include the added custom headers.
This usually happens because you did not write the namespace of your Mapping in config/jsonapi.php.
Double check, if missing, add it and refresh the resource. It should be gone!
Contributions to the package are always welcome!
No open issues yet, or sync has not completed.