Beginners Guide To Yii2 RestAPI

[size="6"]So you want to setup a Rest Application Using Yii2[/size]

What is REST

Basically you input something like


into a url and get back

[ 'name':'wesvault','name':'yii2 company']

that is really all there is to REST. It gets things.

Step 1:

Install Yii2 Framework. Lots of examples on how to do this. I recommend the advanced template or the modified yii2-practical template

Step 2:

Create a Model.

Go to gii , model generator and input your table "companies" at


Step 3:

Create A controller

Same thing in Gii, controller generator

name: CompaniesController

path: frontend\controller\CompaniesController

Step 4:

Edit this controller to use the restful add-ons

namespace frontend\controllers;

use yii\rest\ActiveController;    <--- This says use the rest version of activecontroller 

class ContactsController extends ActiveController   <--- This extends Activecontroller 



	public $modelClass = 'common\models\Contacts';  <-- you need to tell it which model class



Step 5:

Ok now it knows to return a restful action, but how does it handle the incoming url instead of a normal web display.

For this you need to setup the Url Manager, find it in


Add this to the Url Manager

 'urlManager' => [

            'enablePrettyUrl' => true,

            'enableStrictParsing'=> true,   <--- It must match GET , POST etc etc (any one of the rules) 


            'showScriptName' => false,

			'rules'=> [

				['class'=>'yii\rest\UrlRule',  <-- this is the standard rule class

				 'controller'=>'contacts',     <-- which controller   "contacts/{rule}"        

				 'extraPatterns'=>['GET hello' => 'hello',]   <-- I add a custom rule  





Step 6:

Give it a test.

Download POSTMAN or for your browser then enter the url GET : yousite/contacts

you should see a return of some JSON objects. That’s basically it.

Step 7: (custom actions rules)

Ok you have whatever yii2 gives you. But what if you want another rule action like say hello. Above you see I added the rule pattern

Just go to your controller and add in that action normally

public function actionHello()


        return 'hello';


Fire up your browser and try get yoursite/companies/hello. You should see "hello" come back.

Thanks for the guide. Helps beginners like me a lot.

great to start !

is there an easy way to start with real authorization, eg accesscontrol with how to call it?