Rosh_LK Rosh_LK - 2 months ago 46
PHP Question

read JSON input in slim framework

i am new to slim framework following a tutorial i managed to get post data to my API.but when i tried to send data as JSON it gives me an error.I tried to accpt JSON request as follows what is the correct syntax to achive this.i get error as Required field(s) name, email, password is missing or empty

$app->post('/login', function() use ($app) {
// check for required params
$json = $app->request->getBody();
$data = json_decode($json, true);
verifyRequiredParams(array('name','email', 'password'));


how i can get json data from a post request in my API from an JSON array like

{
"name":"usertest",
"email":"xxxx@xxx.xxx",
"password":"xxxxxx"
}


can i use
verifyRequiredParams(array('name','email', 'password'));
and
$name = $app->request->post('name');
if request come as a JSON.

Answer

To read the request data you can use your $data property. It should be an object so you can use it like this:

$name = $data->name;
$email = $data->email;

EDIT:

Use $data = json_decode($json) instead of $data = json_decode($json, true) to convert the json data to object instead of an associative array.

Comments