Sending JSON from the client.


(Mr Banan74) #1

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


(Raffaele Tosti) #2

Mmm I would add a validation rule for the content attribute, something like:




public function rules(){

        return [

            ['content', 'string'],

            [['content'], 'required'],            

        ];

    }



choosing a validator from Here.

Moreover I would add also:




curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));



Another thing you might do is check whether the body request has correctly embedded the json array. Unfortunately REST is stateless and do not holds any session so the Yii2 debug toolbar or XDebug won’t work. For properly debug REST HTTP requests and responses I used to build a proxy server and configure the proxy server on the client connection (my favorite is Mitm proxy) or you may use some sniffing tools like wireshark. Hope it might help, cheers.


(Hehbhehb) #3

add content-type header?