When you send JSON data into a Slim Framework application with a content-type of application/json, then Slim will decode it for you if you use getParsedBody():
|
$app->post("/", function ($request, $response, $args) { $input = $request->getParsedBody(); var_dump($input);exit; }); |
Using curl to test:
|
$ curl -H "Content-Type: application/json" http://localhost:8888 -d '{"foo": "bar"}' array(1) { 'foo' => string(3) "bar" } |
If there's an error however, you get this:
|
$ curl -H "Content-Type: application/json" http://localhost:8888 -d '{foo: bar}' NULL |
If you care about this, you can use json_last_error_msg() and return an error:
|
$app->post("/", function ($request, $response, $args) { $input = $request->getParsedBody(); if ($input === null) { return $response->withJson( ['error_decoding_json' => json_last_error_msg()], 400, JSON_PRETTY_PRINT ); } var_dump($input);exit; }); |
(note – in real code, you should check that the Accept header was a JSON one…) Don't forget the JSON_PRETTY_PRINT… continue reading.
Posted on
16 November 2016 in Slim Framework, Slim Framework 3