Client for easy access of data from {json:api} API. Making requests to API by using PHP HTTP Clients like Guzzle or CURL requires to much code. This package tries to simplify this process, by allowing to get data from API as simply as:
$client = new Client('http://my.api.com');
$response = $client->endpoint('users')->get();
return $response->data;
- PHP >= 5.5.9
composer require javis/json-api-client
Create an instance passing base url and an array of default request options, where you can set up authentication details, etc.
$client = new Client('http://my.api.com',[
'headers' => ['Authorization' => 'Bearer ' . $token]
]);
Or pass an already configured GuzzleHttp\Client()
object.
$http_client = new GuzzleHttp\Client();
$client = new Client('http://my.api.com',[], $http_client);
- get($endpoint)
$client->endpoint('users')->get(); //get users
- post($endpoint)
$client->endpoint('users')->withJsonData([])->post();//store user
- patch($endpoint)
$client->endpoint('users')->withJsonData([])->patch();//do patch request
$client->endpoint('users')->includes(['posts'])->get()
- adds query paraminclude=posts
to request URL. See http://jsonapi.org/format/#fetching-includes$client->endpoint('users')->fields(['user'=> ['id','name']])->get()
- adds query paramfields[users]=id,name
. See http://jsonapi.org/format/#fetching-sparse-fieldsets$client->endpoint('users')->filter(['users'=>['id'=>['eq'=>1]]])->get()
- adds query paramfilter[users][id][eq]=1
. {json:api} is agnostic about filtering, so you can choose your filtering strategy and pass what ever array you want. See http://jsonapi.org/format/#fetching-filtering.$client->endpoint('users')->withQuery(['field'=>1])->get()
- adds query paramfield=1=1
. In theory adding filter, includes, fields and pagination fields should be sufficient.Client::limit($limit, $offset)->get('users')
- add result constraints to query parampage[limit]=x&page[offet]=y
. See http://jsonapi.org/format/#fetching-pagination$client->endpoint('users')->withFormData(['name'=>'John'])->post()
- define post form data. Form data can contain files i.e$client->endpoint('photos')->withFormData(['image'=> $request->file('image')])->post()
.$client->endpoint('users')->withJsonData(['name'=>'John'])->post()
- define post JSON data.
Requests will return Response
object. It will contain public variables:
$resopnse->data
- contains response data.$resopnse->meta
- contains meta data of a response.$resopnse->errors
- contains errors data of a response.$resopnse->status
- holds HTTP status code of request.