{"id":14966614,"url":"https://github.com/tuyakhov/yii2-json-api","last_synced_at":"2025-09-23T15:49:05.282Z","repository":{"id":57073827,"uuid":"54053806","full_name":"tuyakhov/yii2-json-api","owner":"tuyakhov","description":"Implementation of JSON API specification for the Yii framework","archived":false,"fork":false,"pushed_at":"2020-09-23T11:50:29.000Z","size":118,"stargazers_count":139,"open_issues_count":9,"forks_count":18,"subscribers_count":17,"default_branch":"master","last_synced_at":"2025-08-14T04:52:09.458Z","etag":null,"topics":["json","json-api","yii-framework","yii2"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tuyakhov.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-03-16T17:45:39.000Z","updated_at":"2025-04-11T15:34:20.000Z","dependencies_parsed_at":"2022-08-24T10:51:32.819Z","dependency_job_id":null,"html_url":"https://github.com/tuyakhov/yii2-json-api","commit_stats":null,"previous_names":[],"tags_count":25,"template":false,"template_full_name":null,"purl":"pkg:github/tuyakhov/yii2-json-api","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tuyakhov%2Fyii2-json-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tuyakhov%2Fyii2-json-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tuyakhov%2Fyii2-json-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tuyakhov%2Fyii2-json-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tuyakhov","download_url":"https://codeload.github.com/tuyakhov/yii2-json-api/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tuyakhov%2Fyii2-json-api/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":276085248,"owners_count":25582513,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-20T02:00:10.207Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json","json-api","yii-framework","yii2"],"created_at":"2024-09-24T13:36:41.768Z","updated_at":"2025-09-23T15:49:05.246Z","avatar_url":"https://github.com/tuyakhov.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\u003cimg width=\"30%\" src =\"https://jsonapi.org/images/jsonapi.png\" /\u003e\u003c/p\u003e\n\nImplementation of JSON API specification for the Yii framework\n==================================================================\n[![Latest Stable Version](https://poser.pugx.org/tuyakhov/yii2-json-api/v/stable.png)](https://packagist.org/packages/tuyakhov/yii2-json-api)\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/tuyakhov/yii2-json-api/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/tuyakhov/yii2-json-api/?branch=master) [![Build Status](https://scrutinizer-ci.com/g/tuyakhov/yii2-json-api/badges/build.png?b=master)](https://scrutinizer-ci.com/g/tuyakhov/yii2-json-api/build-status/master)\n[![Total Downloads](https://poser.pugx.org/tuyakhov/yii2-json-api/downloads.png)](https://packagist.org/packages/tuyakhov/yii2-json-api)\n\nInstallation\n------------\n\nThe preferred way to install this extension is through [composer](http://getcomposer.org/download/).\n\nEither run\n\n```\nphp composer.phar require --prefer-dist tuyakhov/yii2-json-api \"*\"\n```\n\nor add\n\n```\n\"tuyakhov/yii2-json-api\": \"*\"\n```\n\nto the require section of your `composer.json` file.\n\nData Serializing and Content Negotiation:\n-------------------------------------------\nController:\n```php\nclass Controller extends \\yii\\rest\\Controller\n{\n    public $serializer = 'tuyakhov\\jsonapi\\Serializer';\n    \n    public function behaviors()\n    {\n        return ArrayHelper::merge(parent::behaviors(), [\n            'contentNegotiator' =\u003e [\n                'class' =\u003e ContentNegotiator::className(),\n                'formats' =\u003e [\n                    'application/vnd.api+json' =\u003e Response::FORMAT_JSON,\n                ],\n            ]\n        ]);\n    }\n}\n```\nBy default, the value of `type` is automatically pluralized. \nYou can change this behavior by setting `tuyakhov\\jsonapi\\Serializer::$pluralize` property:\n```php\nclass Controller extends \\yii\\rest\\Controller\n{\n    public $serializer = [\n        'class' =\u003e 'tuyakhov\\jsonapi\\Serializer',\n        'pluralize' =\u003e false,  // makes {\"type\": \"user\"}, instead of {\"type\": \"users\"}\n    ];\n}\n```\nDefining models:\n1) Let's define `User` model and declare an `articles` relation \n```php\nuse tuyakhov\\jsonapi\\ResourceTrait;\nuse tuyakhov\\jsonapi\\ResourceInterface;\n\nclass User extends ActiveRecord implements ResourceInterface\n{\n    use ResourceTrait;\n    \n    public function getArticles()\n    {\n        return $this-\u003ehasMany(Article::className(), ['author_id' =\u003e 'id']);\n    }\n}\n```\n2) Now we need to define `Article` model\n```php\nuse tuyakhov\\jsonapi\\ResourceTrait;\nuse tuyakhov\\jsonapi\\ResourceInterface;\n\nclass Article extends ActiveRecord implements ResourceInterface\n{\n    use ResourceTrait;\n}\n```\n3) As the result `User` model will be serialized into the proper json api resource object:\n```javascript\n{\n  \"data\": {\n    \"type\": \"users\",\n    \"id\": \"1\",\n    \"attributes\": {\n      // ... this user's attributes\n    },\n    \"relationships\": {\n      \"articles\": {\n        // ... this user's articles\n      }\n    }\n  }\n}\n```\nControlling JSON API output\n------------------------------\nThe JSON response is generated by the `tuyakhov\\jsonapi\\JsonApiResponseFormatter` class which will\nuse the `yii\\helpers\\Json` helper internally. This formatter can be configured with different options like\nfor example the `$prettyPrint` option, which is useful on development for\nbetter readable responses, or `$encodeOptions` to control the output\nof the JSON encoding.\n\nThe formatter can be configured in the `yii\\web\\Response::formatters` property of the `response` application\ncomponent in the application configuration like the following:\n\n```php\n'response' =\u003e [\n    // ...\n    'formatters' =\u003e [\n        \\yii\\web\\Response::FORMAT_JSON =\u003e [\n            'class' =\u003e 'tuyakhov\\jsonapi\\JsonApiResponseFormatter',\n            'prettyPrint' =\u003e YII_DEBUG, // use \"pretty\" output in debug mode\n            'encodeOptions' =\u003e JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,\n        ],\n    ],\n],\n```\nLinks\n---------------------------\nYour resource classes may support HATEOAS by implementing the `LinksInterface`.\nThe interface contains `getLinks()` method which should return a list of links.\nTypically, you should return at least the `self` link representing the URL to the resource object itself.\nIn order to appear the links in relationships `getLinks()` method should return `self` link. \nBased on this link each relationship will generate `self` and `related` links. \nBy default it happens by appending a relationship name at the end of the `self` link of the primary model, \nyou can simply change that behavior by overwriting `getRelationshipLinks()` method. \nFor example,\n```php\nclass User extends ActiveRecord implements ResourceInterface, LinksInterface\n{\n    use ResourceTrait;\n    \n    public function getLinks()\n    {\n        return [\n            Link::REL_SELF =\u003e Url::to(['user/view', 'id' =\u003e $this-\u003eid], true),\n        ];\n    }\n}\n```\nAs the result:\n```javascript\n{\n  \"data\": {\n    \"type\": \"users\",\n    \"id\": \"1\",\n    // ... this user's attributes\n    \"relationships\": {\n      \"articles\": {\n        // ... article's data\n        \"links\": {\n            \"self\": {\"href\": \"http://yourdomain.com/users/1/relationships/articles\"},\n            \"related\": {\"href\": \"http://yourdomain.com/users/1/articles\"}\n        }\n      }\n    }\n    \"links\": {\n        \"self\": {\"href\": \"http://yourdomain.com/users/1\"}\n    }\n  }\n}\n```\nPagination\n---------------------------\nThe `page` query parameter family is reserved for pagination.\nThis library implements a page-based strategy and allows the usage of query parameters such as `page[number]` and `page[size]`  \nExample: `http://yourdomain.com/users?page[number]=3\u0026page[size]=10`\n\nEnabling JSON API Input\n---------------------------\nTo 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\n```php\n'request' =\u003e [\n  'parsers' =\u003e [\n      'application/vnd.api+json' =\u003e 'tuyakhov\\jsonapi\\JsonApiParser',\n  ]\n]\n```\nBy default it parses a HTTP request body so that you can populate model attributes with user inputs.\nFor example the request body:\n```javascript\n{\n  \"data\": {\n    \"type\": \"users\",\n    \"id\": \"1\",\n    \"attributes\": {\n        \"first-name\": \"Bob\",\n        \"last-name\": \"Homster\"\n    }\n  }\n}\n```\nWill be resolved into the following array:\n```php\n// var_dump($_POST);\n[\n    \"User\" =\u003e [\n        \"first_name\" =\u003e \"Bob\", \n        \"last_name\" =\u003e \"Homster\"\n    ]\n]\n```\nSo you can access request body by calling `\\Yii::$app-\u003erequest-\u003epost()` and simply populate the model with input data:\n```php\n$model = new User();\n$model-\u003eload(\\Yii::$app-\u003erequest-\u003epost());\n```\nBy default type `users` will be converted into `User` (singular, camelCase) which corresponds to the model's `formName()` method (which you may override).\nYou can override the `JsonApiParser::formNameCallback` property which refers to a callback that converts 'type' member to form name.\nAlso 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.\n\nExamples\n--------\nController:\n```php\nclass UserController extends \\yii\\rest\\Controller\n{\n    public $serializer = 'tuyakhov\\jsonapi\\Serializer';\n\n    /**\n     * @inheritdoc\n     */\n    public function behaviors()\n    {\n        return ArrayHelper::merge(parent::behaviors(), [\n            'contentNegotiator' =\u003e [\n                'class' =\u003e ContentNegotiator::className(),\n                'formats' =\u003e [\n                    'application/vnd.api+json' =\u003e Response::FORMAT_JSON,\n                ],\n            ]\n        ]);\n    }\n    \n    /**\n     * @inheritdoc\n     */\n    public function actions()\n    {\n        return [\n            'create' =\u003e [\n                'class' =\u003e 'tuyakhov\\jsonapi\\actions\\CreateAction',\n                'modelClass' =\u003e ExampleModel::className()\n            ],\n            'update' =\u003e [\n                'class' =\u003e 'tuyakhov\\jsonapi\\actions\\UpdateAction',\n                'modelClass' =\u003e ExampleModel::className()\n            ],\n            'view' =\u003e [\n                'class' =\u003e 'tuyakhov\\jsonapi\\actions\\ViewAction',\n                'modelClass' =\u003e ExampleModel::className(),\n            ],\n            'delete' =\u003e [\n                'class' =\u003e 'tuyakhov\\jsonapi\\actions\\DeleteAction',\n                'modelClass' =\u003e ExampleModel::className(),\n            ],\n            'view-related' =\u003e [\n                'class' =\u003e 'tuyakhov\\jsonapi\\actions\\ViewRelatedAction',\n                'modelClass' =\u003e ExampleModel::className()\n            ],\n            'update-relationship' =\u003e [\n                'class' =\u003e 'tuyakhov\\jsonapi\\actions\\UpdateRelationshipAction',\n                'modelClass' =\u003e ExampleModel::className()\n            ],\n            'delete-relationship' =\u003e [\n                'class' =\u003e 'tuyakhov\\jsonapi\\actions\\DeleteRelationshipAction',\n                'modelClass' =\u003e ExampleModel::className()\n            ],\n            'options' =\u003e [\n                'class' =\u003e 'yii\\rest\\OptionsAction',\n            ],\n        ];\n    }\n}\n\n```\n\nModel:\n```php\nclass User extends ActiveRecord implements LinksInterface, ResourceInterface\n{\n    use ResourceTrait;\n    \n    public function getLinks()\n    {\n        $reflect = new \\ReflectionClass($this);\n        $controller = Inflector::camel2id($reflect-\u003egetShortName());\n        return [\n            Link::REL_SELF =\u003e Url::to([\"$controller/view\", 'id' =\u003e $this-\u003egetId()], true)\n        ];\n    }\n}\n```\n\nConfiguration file `config/main.php`:\n```php\nreturn [\n    // ...\n    'components' =\u003e [\n        'request' =\u003e [\n            'parsers' =\u003e [\n                'application/vnd.api+json' =\u003e 'tuyakhov\\jsonapi\\JsonApiParser',\n            ]\n        ],\n        'response' =\u003e [\n            'format' =\u003e \\yii\\web\\Response::FORMAT_JSON,\n            'formatters' =\u003e [\n                \\yii\\web\\Response::FORMAT_JSON =\u003e 'tuyakhov\\jsonapi\\JsonApiResponseFormatter'\n            ]\n        ],\n        'urlManager' =\u003e [\n            'rules' =\u003e [\n                [\n                    'class' =\u003e 'tuyakhov\\jsonapi\\UrlRule',\n                    'controller' =\u003e ['user'],\n                ],\n\n            ]\n        ]\n        // ...\n    ]\n    // ...\n]\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftuyakhov%2Fyii2-json-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftuyakhov%2Fyii2-json-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftuyakhov%2Fyii2-json-api/lists"}