We have a table that includes of countries so we create a model that called countrylist model
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "countrylist".
*
* @property integer $id
* @property string $iso
* @property string $name
* @property string $nicename
* @property string $iso3
* @property integer $numcode
* @property integer $phonecode
*/
class Countrylist extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'countrylist';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['iso', 'name', 'nicename', 'phonecode'], 'required'],
[['numcode', 'phonecode'], 'integer'],
[['iso'], 'string', 'max' => 2],
[['name', 'nicename'], 'string', 'max' => 80],
[['iso3'], 'string', 'max' => 3]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'iso' => 'Iso',
'name' => 'Name',
'nicename' => 'Nicename',
'iso3' => 'Iso3',
'numcode' => 'Numcode',
'phonecode' => 'Phonecode',
];
}
}
and I create rest webservice for that, we create a controller for restapi and set modelClass variable for our model.
<?php
namespace app\controllers;
use yii\rest\ActiveController;
use Yii;
class CountrylistController extends ActiveController
{
public $modelClass='app\models\Countrylist';
}
?>
for using restapi we need pretty urls and
we add this rule for pretty url
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
['class'=>'yii\rest\UrlRule','controller'=>'countrylist']
],
],
after that we access to can test our rest api as an example
http://localhost/countrylist gives us list of counties.