Skip to content

tuyakhov/yii2-json-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Implementation of JSON API specification for the Yii framework

Latest Stable Version Scrutinizer Code Quality Build Status Total Downloads Installation

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.

Usage

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:

  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']); } }
  1. Now we need to define Article model
use tuyakhov\jsonapi\ResourceTrait; use tuyakhov\jsonapi\ResourceInterface; class Article extends ActiveRecord implements ResourceInterface { use ResourceTrait; }
  1. 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 } } } }

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

About

Implementation of JSON API specification for the Yii framework

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages