2017 © Pedro Peláez
 

yii2-extension yii2-json-api

Implementation of JSON API specification for the Yii framework

image

tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  • Saturday, July 21, 2018
  • by tuyakhov
  • Repository
  • 13 Watchers
  • 113 Stars
  • 7,340 Installations
  • PHP
  • 1 Dependents
  • 0 Suggesters
  • 14 Forks
  • 4 Open issues
  • 36 Versions
  • 15 % Grown

The README.md

, (*1)

Implementation of JSON API specification for the Yii framework

Latest Stable Version Scrutinizer Code Quality Build Status Total Downloads, (*2)

Installation

The preferred way to install this extension is through composer., (*3)

Either run, (*4)

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

or add, (*5)

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

to the require section of your composer.json file., (*6)

Data Serializing and Content Negotiation:

Controller:, (*7)

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:, (*8)

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, (*9)

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, (*10)

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:, (*11)

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

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., (*12)

The formatter can be configured in the yii\web\Response::formatters property of the response application component in the application configuration like the following:, (*13)

'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,
        ],
    ],
],

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,, (*14)

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:, (*15)

{
  "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

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, (*16)

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, (*17)

'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:, (*18)

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

Will be resolved into the following array:, (*19)

// 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:, (*20)

$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., (*21)

Examples

Controller:, (*22)

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:, (*23)

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:, (*24)

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'],
                ],

            ]
        ]
        // ...
    ]
    // ...
]

The Versions

21/07 2018

dev-master

9999999-dev https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

21/07 2018

v1.0.2

1.0.2.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

21/07 2018

dev-fix_empty_resources

dev-fix_empty_resources https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

21/07 2018

v0.1.8

0.1.8.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

21/07 2018

v1.0.1

1.0.1.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

21/07 2018

v1.0.0

1.0.0.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

21/07 2018

v0.1.7

0.1.7.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

14/04 2018

dev-filtering

dev-filtering https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

10/03 2018

v0.1.6

0.1.6.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

10/03 2018

dev-improve_documentation

dev-improve_documentation https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

02/03 2018

dev-add_delete_action

dev-add_delete_action https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

02/03 2018

dev-fix_empty_body

dev-fix_empty_body https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

19/01 2018

v0.1.5

0.1.5.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

19/01 2018

dev-clear_relationships

dev-clear_relationships https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

15/01 2018

dev-error_formatting

dev-error_formatting https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

23/09 2017

dev-inclusion

dev-inclusion https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

31/08 2017

v0.1.4

0.1.4.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

31/08 2017

dev-fix_member_names_error

dev-fix_member_names_error https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

08/07 2017

v0.1.3

0.1.3.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

07/07 2017

dev-remove_duplicates

dev-remove_duplicates https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

06/07 2017

dev-filters

dev-filters https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

15/05 2017

v0.1.2

0.1.2.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

19/03 2017

v0.1.1

0.1.1.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

09/03 2017

dev-rest_actions

dev-rest_actions https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

19/02 2017

v0.1.0

0.1.0.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

12/02 2017

v0.0.11

0.0.11.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

24/12 2016

v0.0.10

0.0.10.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

20/12 2016

v0.0.9

0.0.9.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

17/12 2016

v0.0.8

0.0.8.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

17/12 2016

v0.0.7

0.0.7.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

16/12 2016

v0.0.6

0.0.6.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

27/11 2016

v0.0.5

0.0.5.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

27/11 2016

v0.0.4

0.0.4.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

27/11 2016

v0.0.3

0.0.3.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

12/11 2016

v0.0.2

0.0.2.0 https://github.com/tuyakhov/yii2-json-api

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

The Development Requires

by Anton Tuyakhov

api json rest yii2 json api json-api

14/09 2016

v0.0.1

0.0.1.0

Implementation of JSON API specification for the Yii framework

  Sources   Download

MIT

The Requires

 

by Anton Tuyakhov

api json yii2 json api