PHPackages                             pxc/json-api-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. pxc/json-api-client

ActiveLibrary[API Development](/categories/api)

pxc/json-api-client
===================

A copy of swisnl/json-api-client with headers configuration in request.

v1.0.2(7y ago)1953MITPHPPHP &gt;=7.1

Since Nov 29Pushed 6y agoCompare

[ Source](https://github.com/jgardezi/pxc-json-client)[ Packagist](https://packagist.org/packages/pxc/json-api-client)[ RSS](/packages/pxc-json-api-client/feed)WikiDiscussions master Synced 5d ago

READMEChangelog (3)Dependencies (6)Versions (6)Used By (0)

{ json:api } Client
===================

[](#-jsonapi--client)

[![PHP from Packagist](https://camo.githubusercontent.com/4511e46891b97448b05bbd389a47290cbf4e64cd438a0ea701eb3c1128dee8d6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f737769736e6c2f6a736f6e2d6170692d636c69656e742e737667)](https://packagist.org/packages/swisnl/json-api-client)[![Latest Version on Packagist](https://camo.githubusercontent.com/3e40fe6cdc95550175230eaeac6bcaa3c9379c463a03a2c1429fb54a2aaf17fd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f737769736e6c2f6a736f6e2d6170692d636c69656e742e737667)](https://packagist.org/packages/swisnl/json-api-client)[![Software License](https://camo.githubusercontent.com/16d3a8773cc0ffb56a5263c539f729284e44947c8655c1a99c554ea93ba58482/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f737769736e6c2f6a736f6e2d6170692d636c69656e742e737667)](LICENSE)[![Build Status](https://camo.githubusercontent.com/22beb5bc231e52657151bbaf000c1aa59867b33ad394f486ba8b273cf1237594/68747470733a2f2f7472617669732d63692e6f72672f737769736e6c2f6a736f6e2d6170692d636c69656e742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/swisnl/json-api-client)[![Scrutinizer Coverage](https://camo.githubusercontent.com/19e10e3e7b562b14d1706fb66b08556898ed4191cb12a14314f702c8aa57df91/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f737769736e6c2f6a736f6e2d6170692d636c69656e742e737667)](https://scrutinizer-ci.com/g/swisnl/json-api-client/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/af03740bc87ee6c07383f9dcb9e19076b7898616cbda1980e22ebf16e2f67d6a/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f737769736e6c2f6a736f6e2d6170692d636c69656e742e737667)](https://scrutinizer-ci.com/g/swisnl/json-api-client/?branch=master)[![Made by PrimeXConnect](https://camo.githubusercontent.com/18c919ccf015240637f952c01c589455387b8af316c33432b6cb1a540fe1fdf8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f2546302539462539412538302d6d6164652532306279253230535749532d2532334439303231422e737667)](http://www.primexconnect.com/)

A PHP package for mapping remote [{json:api}](http://jsonapi.org/) resources to Eloquent like models and collections.

A copy of [json-api-client](https://github.com/swisnl/json-api-client/)

### @todo this documentation needs to be updated.

[](#todo-this-documentation-needs-to-be-updated)

Upgrade from 1.0.x to 1.2.x
---------------------------

[](#upgrade-from-10x-to-12x)

The dependency `swisnl/json-api-client` has been upgraded from '0.10.x' to '0.20.x', supporting Lumen 5.8. In your `ServiceProvider`

- Replace `use Swis\JsonApi\Client\Interfaces\ParserInterface; ` with `use Swis\JsonApi\Client\Interfaces\ResponseParserInterface;`
- Replace `use Swis\JsonApi\Client\ItemDocumentSerializer;` with `use PXC\JsonApi\Client\ItemDocumentSerializerInterface;`
- Change the other part of the file accordingly.

Installation
------------

[](#installation)

```
composer require pxc/json-api-client
```

N.B. Make sure you have installed a HTTP Client before you install this package or install one at the same time e.g. `composer require swisnl/json-api-client php-http/guzzle6-adapter`.

### HTTP Client

[](#http-client)

We are decoupled from any HTTP messaging client with the help of [PHP-HTTP](http://php-http.org/). This requires another package providing [php-http/client-implementation](https://packagist.org/providers/php-http/client-implementation). To use Guzzle 6, for example, simply require `php-http/guzzle6-adapter`:

```
composer require php-http/guzzle6-adapter
```

### Laravel Service Provider

[](#laravel-service-provider)

If you are using Laravel &lt; 5.5 or have disabled package auto discover, you must add the service provider to your `config/app.php` file:

```
'providers' => [
    ...,
    \Swis\JsonApi\Client\Providers\ServiceProvider::class,
],
```

Getting started
---------------

[](#getting-started)

You can simply require the client as a dependency and use it in your class. This allows you to, for example, make a repository that uses the [DocumentClient](#documentclient):

```
use Swis\JsonApi\Client\Interfaces\DocumentClientInterface;
use Swis\JsonApi\Client\Interfaces\ItemDocumentInterface;

class BlogRepository
{
    protected $client;

    public function __construct(DocumentClientInterface $client)
    {
        $this->client = $client;
    }

    public function all(array $parameters = [])
    {
        return $this->client->get('blogs?'.http_build_query($parameters));
    }

    public function create(ItemDocumentInterface $document, array $parameters = [])
    {
        return $this->client->post('blogs?'.http_build_query($parameters), $document);
    }

    public function find(string $id, array $parameters = [])
    {
        return $this->client->get('blogs/'.urlencode($id).'?'.http_build_query($parameters));
    }

    public function update(ItemDocumentInterface $document, array $parameters = [])
    {
        return $this->client->patch('blogs/'.urlencode($document->getData()->getId()).'?'.http_build_query($parameters), $document);
    }

    public function delete(string $id, array $parameters = [])
    {
        return $this->client->delete('blogs/'.urlencode($id).'?'.http_build_query($parameters));
    }
}
```

Configuration
-------------

[](#configuration)

The following is the default configuration provided by this package:

```
return [
    /*
    |--------------------------------------------------------------------------
    | Base URI
    |--------------------------------------------------------------------------
    |
    | Specify a base uri which will be prepended to every URI.
    |
    | Default: empty string
    |
    */
    'base_uri' => '',
];
```

### Publish Configuration

[](#publish-configuration)

If you would like to make changes to the default configuration, publish and edit the configuration file:

```
php artisan vendor:publish --provider="Swis\JsonApi\Client\Providers\ServiceProvider" --tag="config"
```

Clients
-------

[](#clients)

This package offers two clients; `DocumentClient` and `Client`.

### DocumentClient

[](#documentclient)

This is the client that you would generally use. Per the [JSON API spec](http://jsonapi.org/format/#document-structure), all requests and responses are documents. Therefore, this client always expects a `\Swis\JsonApi\Client\Interfaces\DocumentInterface` as input when posting data and always returns this same interface. This can be a plain `Document` when there is no data, an `ItemDocument` for an item, a `CollectionDocument` for a collection or an `InvalidResponseDocument` when the server responds with a non 2xx response.

The `DocumentClient` follows the following steps internally:

1. Send the request using your HTTP client;
2. Use [art4/json-api-client](https://github.com/art4/json-api-client) to parse and validate the response;
3. Create the correct document instance;
4. Hydrate every item by using the item model registered with the `TypeMapper` or a `\Swis\JsonApi\Client\Item` as fallback;
5. Hydrate all relationships;
6. Add meta data to the document such as [errors](http://jsonapi.org/format/#errors), [links](http://jsonapi.org/format/#document-links) and [meta](http://jsonapi.org/format/#document-meta).

### Client

[](#client)

This client is a more low level client and can be used, for example, for posting binary data such as images. It can take everything your request factory takes as input data and returns the 'raw' `\Psr\Http\Message\ResponseInterface` wrapped in a `\Swis\JsonApi\Client\Response`. It does not parse or validate the response or hydrate items!

Items
-----

[](#items)

By default, all items are an instance of `\Swis\JsonApi\Client\Item`. The `Item` extends [jenssegers/model](https://github.com/jenssegers/model), which provides a Laravel Eloquent-like base class. Please see it's documentation about the features it provides. You can define your own models by extending `\Swis\JsonApi\Client\Item` or by implementing the `\Swis\JsonApi\Client\Interfaces\ItemInterface` yourself. This can be useful if you want to define, for example, hidden attributes, casts or get/set mutators. If you use custom models, you must register them with the [TypeMapper](#typemapper).

### Relations

[](#relations)

On top of [jenssegers/model](https://github.com/jenssegers/model), this package has implemented [Laravel Eloquent-like relations](https://laravel.com/docs/eloquent-relationships). These relations provide a fluent interface to retrieve the related items. There are currently four relations available:

- `HasOneRelation`
- `HasManyRelation`
- `MorphToRelation`
- `MorphToManyRelation`

Please see the following example about defining the relationships:

```
use Swis\JsonApi\Client\Item;

class AuthorItem extends Item
{
    protected $type = 'author';

    public function blogs()
    {
        return $this->hasMany(BlogItem::class);
    }
}

class BlogItem extends Item
{
    protected $type = 'blog';

    public function author()
    {
        return $this->hasOne(AuthorItem::class);
    }
}
```

Collections
-----------

[](#collections)

This package uses [Laravel Collections](https://laravel.com/docs/collections) as a wrapper for item arrays.

TypeMapper
----------

[](#typemapper)

All custom models must be registered with the `TypeMapper`. This `TypeMapper` maps, as the name suggests, JSON API types to custom [item models](#item-models).

### Mapping types

[](#mapping-types)

You can manually register items with the `\Swis\JsonApi\Client\TypeMapper` or use the supplied `\Swis\JsonApi\Client\Providers\TypeMapperServiceProvider`:

```
use Swis\JsonApi\Client\Providers\TypeMapperServiceProvider as BaseTypeMapperServiceProvider;

class TypeMapperServiceProvider extends BaseTypeMapperServiceProvider
{
    /**
     * A list of class names implementing \Swis\JsonApi\Client\Interfaces\ItemInterface.
     *
     * @var string[]
     */
    protected $items = [
        \App\Items\Author::class,
        \App\Items\Blog::class,
        \App\Items\Comment::class,
    ];
}
```

Service Provider
----------------

[](#service-provider)

The `\Swis\JsonApi\Client\Providers\ServiceProvider` registers the `TypeMapper`, `JsonApi\Parser` and both clients; `Client` and `DocumentClient`. Each section can be overwritten to allow extended customization.

### Bind TypeMapper

[](#bind-typemapper)

The service provider registers the `TypeMapper` as a singleton so your entire application has the same mappings available.

### Bind Clients

[](#bind-clients)

The service provider registers the `Client` and `DocumentClient` to your application. By default it uses [php-http/discovery](https://github.com/php-http/discovery) to find a HTTP client and message factory. You can specify your own message factory by overwriting the `getMessageFactory()` method and your own HTTP client by overwriting the `getHttpClient()` method. The first should return a message factory and the latter should return a HTTP client, both implementing HTTPlug. These methods are the perfect place to add extra options to your HTTP client or register a mock HTTP client for your tests:

```
protected function getHttpClient(): HttpClient
{
    if (app()->environment('testing')) {
        return new \Swis\Http\Fixture\Client(
            new \Swis\Http\Fixture\ResponseBuilder('/path/to/fixtures');
        );
    }

    return \Http\Adapter\Guzzle6\Client::createWithConfig(
        [
            'timeout' => 2,
        ]
    );
}
```

N.B. This example uses our [swisnl/php-http-fixture-client](https://github.com/swisnl/php-http-fixture-client) when in testing environment. This package allows you to easily mock requests with static fixtures. Definitely worth a try!

If you register your own service provider and use package auto discover, don't forget to exclude this package in your `package.json`:

```
"extra": {
  "laravel": {
    "dont-discover": [
      "swisnl/json-api-client"
    ]
  }
},
```

Change log
----------

[](#change-log)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Testing
-------

[](#testing)

```
composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CODE\_OF\_CONDUCT](CODE_OF_CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

SWIS
----

[](#swis)

[SWIS](https://www.swis.nl) is a web agency from Leiden, the Netherlands. We love working with open source software.

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 50% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~89 days

Total

5

Last Release

2368d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2758203cc3973ee4daddc62bcc5b3c053e27cbce1ab2db842854c99c3366443b?d=identicon)[jgardezi](/maintainers/jgardezi)

---

Top Contributors

[![richdho](https://avatars.githubusercontent.com/u/3889338?v=4)](https://github.com/richdho "richdho (6 commits)")[![jgardezi](https://avatars.githubusercontent.com/u/1083698?v=4)](https://github.com/jgardezi "jgardezi (3 commits)")[![QuyenHoang06](https://avatars.githubusercontent.com/u/19359287?v=4)](https://github.com/QuyenHoang06 "QuyenHoang06 (3 commits)")

---

Tags

clientjson-apilaravellaravel-packagelumenphp7

### Embed Badge

![Health badge](/badges/pxc-json-api-client/health.svg)

```
[![Health](https://phpackages.com/badges/pxc-json-api-client/health.svg)](https://phpackages.com/packages/pxc-json-api-client)
```

###  Alternatives

[janu-software/facebook-php-sdk

Alternative toolkit for Facebook Graph API

71684.8k2](/packages/janu-software-facebook-php-sdk)[apigee/apigee-client-php

Client library for connecting to the Apigee Edge API.

27558.7k3](/packages/apigee-apigee-client-php)[php-heroku-client/php-heroku-client

A PHP client for the Heroku Platform API

24404.8k4](/packages/php-heroku-client-php-heroku-client)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)[swader/diffbot-php-client

A PHP wrapper for using Diffbot's API

5328.5k](/packages/swader-diffbot-php-client)[dhope0000/lxd

PHP-based API wrapper for LXD REST API.

136.2k](/packages/dhope0000-lxd)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
