PHPackages                             tuyakhov/yii2-json-api - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. tuyakhov/yii2-json-api

ActiveYii2-extension[HTTP &amp; Networking](/categories/http)

tuyakhov/yii2-json-api
======================

Implementation of JSON API specification for the Yii framework

v1.0.5(2w ago)140119.0k↓50.7%18[6 issues](https://github.com/tuyakhov/yii2-json-api/issues)[3 PRs](https://github.com/tuyakhov/yii2-json-api/pulls)MITPHPCI failing

Since Sep 14Pushed 2w ago17 watchersCompare

[ Source](https://github.com/tuyakhov/yii2-json-api)[ Packagist](https://packagist.org/packages/tuyakhov/yii2-json-api)[ Docs](https://github.com/tuyakhov/yii2-json-api)[ RSS](/packages/tuyakhov-yii2-json-api/feed)WikiDiscussions master Synced 4d ago

READMEChangelog (10)Dependencies (4)Versions (40)Used By (0)

[![](https://camo.githubusercontent.com/e2a5125f0c8ff74081909cba3305e8752cfb5942bda7fb238c5fe49193a169a3/68747470733a2f2f6a736f6e6170692e6f72672f696d616765732f6a736f6e6170692e706e67)](https://camo.githubusercontent.com/e2a5125f0c8ff74081909cba3305e8752cfb5942bda7fb238c5fe49193a169a3/68747470733a2f2f6a736f6e6170692e6f72672f696d616765732f6a736f6e6170692e706e67)

Implementation of JSON API specification for the Yii framework
==============================================================

[](#implementation-of-json-api-specification-for-the-yii-framework)

[![Latest Stable Version](https://camo.githubusercontent.com/0d31dc20956313548360898a156f56f53e66a34bb0539dcc74dd8527d5ad1609/68747470733a2f2f706f7365722e707567782e6f72672f747579616b686f762f796969322d6a736f6e2d6170692f762f737461626c652e706e67)](https://packagist.org/packages/tuyakhov/yii2-json-api)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/4896f08f2acbf57bce541afcb4b85bfd4e338b186e95bbf0e7e91fa609393673/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f747579616b686f762f796969322d6a736f6e2d6170692f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/tuyakhov/yii2-json-api/?branch=master) [![Build Status](https://camo.githubusercontent.com/8b42204623dff6149775aab2e8166127c234b63aa317a912c80859f23fa1ab08/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f747579616b686f762f796969322d6a736f6e2d6170692f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/tuyakhov/yii2-json-api/build-status/master)[![Total Downloads](https://camo.githubusercontent.com/6aa7680f23071c7d3267039f3c68d5fb76b00e97642fd60baceaa7e50948c8c8/68747470733a2f2f706f7365722e707567782e6f72672f747579616b686f762f796969322d6a736f6e2d6170692f646f776e6c6f6164732e706e67)](https://packagist.org/packages/tuyakhov/yii2-json-api)

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

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist tuyakhov/yii2-json-api "*"

```

or add

```
"tuyakhov/yii2-json-api": "*"

```

to the require section of your `composer.json` file.

Data Serializing and Content Negotiation:
-----------------------------------------

[](#data-serializing-and-content-negotiation)

Controller:

```
class Controller extends \yii\rest\Controller
{
    public $serializer = 'tuyakhov\jsonapi\Serializer';

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/vnd.api+json' => Response::FORMAT_JSON,
                ],
            ]
        ]);
    }
}
```

By default, the value of `type` is automatically pluralized. You can change this behavior by setting `tuyakhov\jsonapi\Serializer::$pluralize` property:

```
class Controller extends \yii\rest\Controller
{
    public $serializer = [
        'class' => 'tuyakhov\jsonapi\Serializer',
        'pluralize' => false,  // makes {"type": "user"}, instead of {"type": "users"}
    ];
}
```

Defining models:

1. Let's define `User` model and declare an `articles` relation

```
use tuyakhov\jsonapi\ResourceTrait;
use tuyakhov\jsonapi\ResourceInterface;

class User extends ActiveRecord implements ResourceInterface
{
    use ResourceTrait;

    public function getArticles()
    {
        return $this->hasMany(Article::className(), ['author_id' => 'id']);
    }
}
```

2. Now we need to define `Article` model

```
use tuyakhov\jsonapi\ResourceTrait;
use tuyakhov\jsonapi\ResourceInterface;

class Article extends ActiveRecord implements ResourceInterface
{
    use ResourceTrait;
}
```

3. As the result `User` model will be serialized into the proper json api resource object:

```
{
  "data": {
    "type": "users",
    "id": "1",
    "attributes": {
      // ... this user's attributes
    },
    "relationships": {
      "articles": {
        // ... this user's articles
      }
    }
  }
}
```

Controlling JSON API output
---------------------------

[](#controlling-json-api-output)

The JSON response is generated by the `tuyakhov\jsonapi\JsonApiResponseFormatter` class which will use the `yii\helpers\Json` helper internally. This formatter can be configured with different options like for example the `$prettyPrint` option, which is useful on development for better readable responses, or `$encodeOptions` to control the output of the JSON encoding.

The formatter can be configured in the `yii\web\Response::formatters` property of the `response` application component in the application configuration like the following:

```
'response' => [
    // ...
    'formatters' => [
        \yii\web\Response::FORMAT_JSON => [
            'class' => 'tuyakhov\jsonapi\JsonApiResponseFormatter',
            'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
            'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
        ],
    ],
],
```

Links
-----

[](#links)

Your resource classes may support HATEOAS by implementing the `LinksInterface`. The interface contains `getLinks()` method which should return a list of links. Typically, you should return at least the `self` link representing the URL to the resource object itself. In order to appear the links in relationships `getLinks()` method should return `self` link. Based on this link each relationship will generate `self` and `related` links. By default it happens by appending a relationship name at the end of the `self` link of the primary model, you can simply change that behavior by overwriting `getRelationshipLinks()` method. For example,

```
class User extends ActiveRecord implements ResourceInterface, LinksInterface
{
    use ResourceTrait;

    public function getLinks()
    {
        return [
            Link::REL_SELF => Url::to(['user/view', 'id' => $this->id], true),
        ];
    }
}
```

As the result:

```
{
  "data": {
    "type": "users",
    "id": "1",
    // ... this user's attributes
    "relationships": {
      "articles": {
        // ... article's data
        "links": {
            "self": {"href": "http://yourdomain.com/users/1/relationships/articles"},
            "related": {"href": "http://yourdomain.com/users/1/articles"}
        }
      }
    }
    "links": {
        "self": {"href": "http://yourdomain.com/users/1"}
    }
  }
}
```

Pagination
----------

[](#pagination)

The `page` query parameter family is reserved for pagination. This library implements a page-based strategy and allows the usage of query parameters such as `page[number]` and `page[size]`
Example: `http://yourdomain.com/users?page[number]=3&page[size]=10`

Enabling JSON API Input
-----------------------

[](#enabling-json-api-input)

To let the API accept input data in JSON API format, configure the \[\[yii\\web\\Request::$parsers|parsers\]\] property of the request application component to use the \[\[tuyakhov\\jsonapi\\JsonApiParser\]\] for JSON input

```
'request' => [
  'parsers' => [
      'application/vnd.api+json' => 'tuyakhov\jsonapi\JsonApiParser',
  ]
]
```

By default it parses a HTTP request body so that you can populate model attributes with user inputs. For example the request body:

```
{
  "data": {
    "type": "users",
    "id": "1",
    "attributes": {
        "first-name": "Bob",
        "last-name": "Homster"
    }
  }
}
```

Will be resolved into the following array:

```
// var_dump($_POST);
[
    "User" => [
        "first_name" => "Bob",
        "last_name" => "Homster"
    ]
]
```

So you can access request body by calling `\Yii::$app->request->post()` and simply populate the model with input data:

```
$model = new User();
$model->load(\Yii::$app->request->post());
```

By default type `users` will be converted into `User` (singular, camelCase) which corresponds to the model's `formName()` method (which you may override). You can override the `JsonApiParser::formNameCallback` property which refers to a callback that converts 'type' member to form name. Also you could change the default behavior for conversion of member names to variable names ('first-name' converts into 'first\_name') by setting `JsonApiParser::memberNameCallback` property.

Examples
--------

[](#examples)

Controller:

```
class UserController extends \yii\rest\Controller
{
    public $serializer = 'tuyakhov\jsonapi\Serializer';

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/vnd.api+json' => Response::FORMAT_JSON,
                ],
            ]
        ]);
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'create' => [
                'class' => 'tuyakhov\jsonapi\actions\CreateAction',
                'modelClass' => ExampleModel::className()
            ],
            'update' => [
                'class' => 'tuyakhov\jsonapi\actions\UpdateAction',
                'modelClass' => ExampleModel::className()
            ],
            'view' => [
                'class' => 'tuyakhov\jsonapi\actions\ViewAction',
                'modelClass' => ExampleModel::className(),
            ],
            'delete' => [
                'class' => 'tuyakhov\jsonapi\actions\DeleteAction',
                'modelClass' => ExampleModel::className(),
            ],
            'view-related' => [
                'class' => 'tuyakhov\jsonapi\actions\ViewRelatedAction',
                'modelClass' => ExampleModel::className()
            ],
            'update-relationship' => [
                'class' => 'tuyakhov\jsonapi\actions\UpdateRelationshipAction',
                'modelClass' => ExampleModel::className()
            ],
            'delete-relationship' => [
                'class' => 'tuyakhov\jsonapi\actions\DeleteRelationshipAction',
                'modelClass' => ExampleModel::className()
            ],
            'options' => [
                'class' => 'yii\rest\OptionsAction',
            ],
        ];
    }
}
```

Model:

```
class User extends ActiveRecord implements LinksInterface, ResourceInterface
{
    use ResourceTrait;

    public function getLinks()
    {
        $reflect = new \ReflectionClass($this);
        $controller = Inflector::camel2id($reflect->getShortName());
        return [
            Link::REL_SELF => Url::to(["$controller/view", 'id' => $this->getId()], true)
        ];
    }
}
```

Configuration file `config/main.php`:

```
return [
    // ...
    'components' => [
        'request' => [
            'parsers' => [
                'application/vnd.api+json' => 'tuyakhov\jsonapi\JsonApiParser',
            ]
        ],
        'response' => [
            'format' => \yii\web\Response::FORMAT_JSON,
            'formatters' => [
                \yii\web\Response::FORMAT_JSON => 'tuyakhov\jsonapi\JsonApiResponseFormatter'
            ]
        ],
        'urlManager' => [
            'rules' => [
                [
                    'class' => 'tuyakhov\jsonapi\UrlRule',
                    'controller' => ['user'],
                ],

            ]
        ]
        // ...
    ]
    // ...
]
```

###  Health Score

64

—

FairBetter than 99% of packages

Maintenance95

Actively maintained with recent releases

Popularity48

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor1

Top contributor holds 96.1% 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 ~142 days

Recently: every ~722 days

Total

26

Last Release

18d ago

Major Versions

v0.1.7 → v1.0.02018-07-21

v0.1.8 → v1.0.12018-07-21

### Community

Maintainers

![](https://www.gravatar.com/avatar/217d79b2ef3dda6048f6368e331106b1d6321be4af345642f6f6b66bf8c7161b?d=identicon)[tuyakhov](/maintainers/tuyakhov)

---

Top Contributors

[![tuyakhov](https://avatars.githubusercontent.com/u/7713205?v=4)](https://github.com/tuyakhov "tuyakhov (73 commits)")[![acorncom](https://avatars.githubusercontent.com/u/802505?v=4)](https://github.com/acorncom "acorncom (1 commits)")[![kfreiman](https://avatars.githubusercontent.com/u/2056294?v=4)](https://github.com/kfreiman "kfreiman (1 commits)")[![patrick-yi-82](https://avatars.githubusercontent.com/u/2878951?v=4)](https://github.com/patrick-yi-82 "patrick-yi-82 (1 commits)")

---

Tags

jsonjson-apiyii-frameworkyii2jsonapirestyii2JSON-API

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/tuyakhov-yii2-json-api/health.svg)

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

PHPackages © 2026

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