2

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?

PrototypeX7
  • 154
  • 2
  • 10

2 Answers2

6

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
Luigi Pressello
  • 937
  • 4
  • 9
0

Seems that the problem is in the data that you're getting from the client. You're receiving a sort of var_dump or var_export output as the user in this case. According with the data that you receive, I would search something like this in your client code:

<?php var_export([json_encode($data) => '',],true);

On the server side the body can't be parsed because it's not a correct JSON string.

dlopez
  • 969
  • 5
  • 17
  • I don't modify the data on my client, expect for what I already posted. I send it with: `curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );` – PrototypeX7 May 11 '16 at 15:05
  • Can you update your question with the client side code? From my point of view, the data is being modified in some point. Also, as @LuigiPresello said, check that you're sending your data with the correct content type headers (this will help the framework to do a better data format conversion) – dlopez May 11 '16 at 15:09