Hi. I used REST API in my project.
Created table elements(id, content)
Created Module
Element
namespace app\models;
use yii\db\ActiveRecord;
class Element extends ActiveRecord{
public static function tableName(){
return 'elements';
}
public function rules(){
return [
[['content'], 'required'],
];
}
public function fields()
{
return ['id', 'content'];
}
Creatd Controller
ElementController
namespace app\controllers;
use yii\rest\ActiveController;
use app\models\Element;
use yii\rest\Controller;
class ElementController extends ActiveController{
public $modelClass = 'app\models\Element';
public function actions()
{
$actions = parent::actions();
return $actions;
}
}
On client create curl
$url = "api.test.loc/elements";
$request_data = ['content' => 'dddd'];
$json = json_encode($request_data);
print_r($json);
echo '<br>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
print_r($response);
But my api sends me an error:
[{"field":"content","message":"Content cannot be blank."}]
Help me. How to write a json correctly on client???
Sorry for the grammar - I do not know much English