I tried to create a REST API by referring Yii2 REST GUIDE but unfortunately I got only GET method working.
Example URL:
apart from the above URL everything else gives me a NOT FOUND (404) error page (Not even a JSON response).
app\controllers\EmployeeController.php
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class EmployeeController extends ActiveController
{
public $modelClass = 'app\models\Employee';
/**
* @return array
*/
protected function verbs()
{
return [
'index' => ['GET', 'HEAD'],
'view' => ['GET', 'HEAD'],
'create' => ['POST'],
'update' => ['PUT', 'PATCH'],
'delete' => ['DELETE'],
];
}
}
app\models\Employee.php
<?php
namespace app\models;
use Yii;
class Employee extends \yii\db\ActiveRecord
{
public $primaryKey = 'emp_no';
/**
* @inheritdoc
*/
public static function tableName()
{
return 'employees';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['emp_no', 'birth_date', 'first_name', 'last_name', 'gender', 'hire_date'], 'required'],
[['emp_no'], 'integer'],
[['birth_date', 'hire_date'], 'safe'],
[['gender'], 'string'],
[['first_name'], 'string', 'max' => 14],
[['last_name'], 'string', 'max' => 16],
[['emp_no'], 'unique'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'emp_no' => 'Emp No',
'birth_date' => 'Birth Date',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'gender' => 'Gender',
'hire_date' => 'Hire Date',
];
}
web.php Configuration
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'employer'],
],
],
.htaccess
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
I hope that I have provided every relevant information to solve my problem. Thanks in advance. :-)
You have defined the name of the controller as employer
whereas it should be employee
if i am not wrong and that is not a typo writing the code here
Change to the following
['class' => 'yii\rest\UrlRule', 'controller' => 'employee'],