How to access a JSON request body of a POST request in Slim? How to access a JSON request body of a POST request in Slim? json json

How to access a JSON request body of a POST request in Slim?


Generally speaking, you can access the POST parameters individually in one of two ways:

$paramValue = $application->request->params('paramName');

or

$paramValue = $application->request->post('paramName');

More info is available in the documentation: http://docs.slimframework.com/#Request-Variables

When JSON is sent in a POST, you have to access the information from the request body, for example:

$app->post('/some/path', function () use ($app) {    $json = $app->request->getBody();    $data = json_decode($json, true); // parse the JSON into an assoc. array    // do other tasks});


"Slim can parse JSON, XML, and URL-encoded data out of the box" - http://www.slimframework.com/docs/objects/request.html under "The Request Body".

Easiest way to handle a request in any body form is via the "getParsedBody()". This will do guillermoandrae example but on 1 line instead of 2.

Example:

$allPostVars = $application->request->getParsedBody();

Then you can access any parameters by their key in the array given.

$someVariable = $allPostVars['someVariable'];