Download the PHP package nilportugues/laravel5-json-api without Composer
On this page you can find all versions of the php package nilportugues/laravel5-json-api. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download nilportugues/laravel5-json-api
More information about nilportugues/laravel5-json-api
Files in nilportugues/laravel5-json-api
Package laravel5-json-api
Short Description Laravel 5 JSON API Transformer Package
License MIT
Homepage http://nilportugues.com
Informations about the package laravel5-json-api
Laravel 5 JSON API Server Package
Compatible with Laravel 5.0, 5.1 & 5.2
- Package provides a full implementation of the JSON API specification, and is featured on the official site!
- A JSON API Transformer that will allow you to convert any mapped object into a valid JSON API resource.
- Controller boilerplate to write a fully compiliant JSON API Server using your exisiting Eloquent Models.
- Works for Laravel 5 and Lumen frameworks.
- Installation
- Configuration (Laravel 5 & Lumen)
- Configuration for Laravel 5
- Step 1: Add the Service Provider
- Step 2: Defining routes
- Step 3: Definition
- Step 4: Usage
- Configuration for Lumen
- Step 1: Add the Service Provider
- Step 2: Defining routes
- Step 3: Definition
- Step 4: Usage
- JsonApiController
- Examples: Consuming the API
- GET
- POST
- PUT
- PATCH
- DELETE
- GET Query Params: include, fields, sort and page
- POST/PUT/PATCH with Relationships
- Custom Response Headers
- Common Errors and Solutions
Installation
Use Composer to install the package:
Now run the following artisan command:
Configuration (Laravel 5 & Lumen)
For 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, Employees
will be using an Eloquent feature, appended fields
to demonstrate how it is possible to make the most of Eloquent and this package all together.
Configuration for Laravel 5
Step 1: Add the Service Provider
Open up config/app.php
and add the following line under providers
array:
Step 2: Defining routes
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:
Step 3: Definition
First, let's define the Models for Employees
and Orders
using Eloquent.
Employees (Eloquent Model)
Employees SQL
Orders (Eloquent Model)
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
Step 4: Usage
Create file config/jsonapi.php
. This file should return an array returning all the class mappings.
Configuration for Lumen
Step 1: Add the Service Provider
Open up bootstrap/app.php
and add the following lines before the return $app;
statement:
Also, enable Facades by uncommenting:
Step 2: Defining routes
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:
Step 3: Definition
Same as Laravel 5.
Step 4: Usage
Same as Laravel 5.
JsonApiController
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
.
In case you need to overwrite any default behaviour, the JsonApiController methods are:
But wait! We're missing out one action, EmployeesController@getOrdersByEmployee
.
As the name suggests, it should list orders, so the behaviour should be the same as the one of ListAction
.
If you look inside the listAction
you'll find a code similar to the one below, but we just ajusted the behaviour and used it in our controller to support an additional action:
And you're ready to go. Yes, it is THAT simple!
Examples: Consuming the API
GET
This is the output for EmployeesController@getAction
being consumed from command-line method issuing: curl -X GET "http://localhost:9000/employees/1"
.
Output:
POST
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 POST
to the following URI http://localhost:9000/employees
:
Will produce:
Notice how 201 HTTP Status Code is returned and Location header too. Also attachments
is not there anymore, and full_name
was displayed.
PUT
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 PUT
to the following URI http://localhost:9000/employees/10
:
Will produce:
PATCH
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
:
Will produce:
DELETE
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:
And notice how response will be empty:
GET Query Params: include, fields, sort and page
According to the standard, for GET method, it is possible to:
- Show only those fields requested using
fields
query parameter.- &fields[resource]=field1,field2
For instance, passing /employees/10?fields[employee]=company,first_name
will produce the following output:
- Show only those
include
resources by passing in the relationship between them separated by dot, or just pass in list of resources separated by comma.- &include=resource1
- &include=resource1.resource2,resource2.resource3
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 indata[type]
member. If it starts with a-
order isDESCENDING
, otherwise it'sASCENDING
.- &sort=field1,-field2
- &sort=-field1,field2
For instance: /employees?sort=surname,-first_name
- Pagination is also defined to allow doing page pagination, cursor pagination or offset pagination.
- &page[number]
- &page[limit]
- &page[cursor]
- &page[offset]
- &page[size]
For instance: /employees?page[number]=1&page[size]=10
POST/PUT/PATCH with Relationships
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 Order
too.
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
Orders (Eloquent Model) with $fillable
Custom Response Headers
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:
Now all supported actions will include the added custom headers.
Common Errors and Solutions
"Undefined index: @type"
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!
Contribute
Contributions to the package are always welcome!
- Report any bugs or issues you find on the issue tracker.
- You can grab the source code at the package's Git repository.
Support
Get in touch with me using one of the following means:
- Emailing me at [email protected]
- Opening an Issue
Authors
License
The code base is licensed under the MIT license.
All versions of laravel5-json-api with dependencies
symfony/psr-http-message-bridge Version ~0.1
nilportugues/serializer-eloquent Version ~1.0