The quickest way to add RestAPI to your Yii 2 app. Part 1

The example given in Yii 2 Guide is of a low quality, because it It requires User model based on database, not a file. And the guide mixes two things together:

  • Yii 2 Basic Template, which is used in this example, has User model, but based on itself (on a file — list of users is given as an array)
  • Yii 2 Advanced Template has User model based on database, but it uses a multi-application concept in the same time and adding REST support, like shown in this example, isn’t possible.

As an effect, people who just starts their journey with Yii 2 and REST are often confused and finds official example not working in their side.

This article deals with this problem and show how to enable REST in Yii 2 Basic Project Template by using some model (database-based) other than User model.


We need:

And that is pretty much everything since Yii 2 is doing most of the “dirty stuff” for you, behind the scenes. And thus coding really simple RESTful apps is… really simple! :)

The model

I used the one from the Guide, but you can use pretty much anyone:


namespace app\models;

use yii\db\ActiveRecord;

class Country extends ActiveRecord

It’s empty because (again!) Yii 2 is doing all the stuff for you.

Name it as Country.php and put it to models folder of your Yii 2 Basic app.

The controller

I’ve created one also based on the guide. I only changed paths to use Country model instead of User model, which doesn’t work in Yii 2 Basic App Template:

namespace app\controllers;
use yii\rest\ActiveController;

class CountryController extends ActiveController
    public $modelClass = 'app\models\Country';

Put it to controllers folder under CountryController.php file name.

Let’s rock!

Here you have an example of calling above created endpoint, as tested in Insomia, curl and directly in browser:

You can already see another powerful feature of Yii 2’s RESTful apps — response content negotiation.

Browser requests XML and receives response in this format (left part of the image). Insomia was force-configured to request response in JSON (middle part of the image). Which turned out to be not necessary, because yii\rest\Controller responds with JSON by default (right part of the image — curl).

Leave a Reply