I'm am using the Slim Framework v3 and have some problems with accessing the JSON data I'm sending from a browser client to my REST API.
Currently I'm using $request->getParsedBody();
to access the data, but all it returns is a string and I don't want to parse it, because I think there's a better solution for this problem.
Here's what is sent by the client:
$data = array ();
$data ["key1"] = "value1";
$data ["key2"] = "value2";
$data ["key3"] = "value3";
$data = json_encode ( $data );
This produces {"key1":"value1","key2":"value2","key3":"value3"}
What happens on the server?
$app->post ( '/somePath', function ($request, $response) {
$body = $request->getParsedBody();
var_dump($body);
return $response;
});
The var_dump();
is producing the following output:
string(86) "array(1) {
["{"key1":"value1","key2":"value2","key3":"value3"}"]=>
string(0) ""
}
"
As you can see, $request->getParsedBody();
is returning a string.
Is there any better way to do this?
I already tried to use $request->getBody();
, but that returns an object of the type Slim\Http\RequestBody and has only protected variables. I haven't found any function to access these protected variables.
Please remember that I'm using Slim v3, they have changed a lot of things from v2.
If there is no better way, do you have suggestions how to parse it the best way?
As reported by the Slim 3 docs:
JSON requests are converted into associative arrays with json_decode($input, true).
So getParsedBody is definitely the way to go.
Instead, have you check the request type set by your client? It should be application/json
in order to make the Slim request object do the correct interpretation of the raw body.
eg:
Content-Type: application/json