The preferred way to install this extension is through composer.
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.
Once the extension is installed, simply use it in your code by : 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, ], ] ]); } }Defining models:
- Let's define
Usermodel and declare anarticlesrelation
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']); } }- Now we need to define
Articlemodel
use tuyakhov\jsonapi\ResourceTrait; use tuyakhov\jsonapi\ResourceInterface; class Article extends ActiveRecord implements ResourceInterface { use ResourceTrait; }- As the result
Usermodel 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 } } } }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', ] ]


